gfarhat has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm trying to add new values to classpath using the following: system("export CLASSPATH=\$CLASSPATH:/usr/users/private"); but the new value is not added when i try to print $CLASSPATH Is there anyway to do it?

Replies are listed 'Best First'.
Re: export classpath in perl script
by ikegami (Patriarch) on Mar 25, 2008 at 17:08 UTC

    You can only change the environment of your own process and yet-to-be-created children.

    In your code, you launch sh, tell the process to change one of its environment variables, and then the process exits along with environment.

    The following will set the env var for the Perl process and any child it launches (via system, for example):

    $ENV{CLASSPATH} = "$ENV{CLASSPATH}:/usr/users/private";

    If you want to change the parent's environment, you'll need to send commands to the parent process that it understands. Here's an example for Windows systems:

    >type script.bat @echo off set testa= set testb= echo testa=%testa% echo testb=%testb% for /f "usebackq delims=" %%f in (`perl script.pl`) do %%f echo testa=%testa% echo testb=%testb% >type script.pl print("set testa=abc\n"); print("set testb=def\n"); >script testa= testb= testa=abc testb=def
Re: export classpath in perl script
by Corion (Patriarch) on Mar 25, 2008 at 17:08 UTC

    export is a shell built-in and it doesn't work the way you're using it. system launches a shell, which executes the export command and then exits. After the shell has ended, all changes and exports vanish as well.

    Manipulating the environment of child processes is done through manipulating the %ENV hash in Perl:

    $ENV{CLASSPATH} = "$ENV{CLASSPATH}:/usr/users/private";
Re: export classpath in perl script
by Sinistral (Monsignor) on Mar 25, 2008 at 17:10 UTC
    When you run your system, a subshell is created, the export is run, and the subshell immediately exits. Thus, the value is not changed in the scope of the running Perl script. If you want to change the environment variable's value at the level of the Perl script, you can use %ENV:
    $ENV{'CLASSPATH'} = "$ENV{'CLASSPATH'}:/usr/users/private";
    Any Java that you then invoke from Perl using system or backticks will have the new CLASSPATH. Note that when the Perl script exits, the CLASSPATH will remain at its original value, not the value set within the Perl script.