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

I have a shell script being called from a perl. I want to return a variable from this shell to the mail perl script. I am doing this in shell:
export bad_code=bad_codeZ echo "\$bad_code is $bad_code"
and when I do this in my main perl script:
$bad_codeP = $ENV{"bad_code"}; chomp $bad_codeP; print "\$bad_codeP is $bad_codeP \n";
the $bad_codeP returns blank. Here is the log: $bad_codeP is what am I missing? Any help is appreciated. thx

Replies are listed 'Best First'.
Re: passing a variable from shell script to the main perl
by ikegami (Patriarch) on Apr 05, 2011 at 21:48 UTC

    Each process has its own environment. A process gets its environment from its parent. Changing the shell's environment in no way affects perl's. The only possible processes it can affect are children of the shell, and only those that are created after the change takes place.

    If you want to send data to a parent process, it's commonly done via a pipe connected to the child's STDOUT.

    $ perl -e'print "Got: ", `sh -c "echo foo"`;' Got: foo
Re: passing a variable from shell script to the main perl
by wind (Priest) on Apr 05, 2011 at 21:42 UTC

    Just use backticks.

    my $results = `shell.sh`;

    Changes to your %ENV made by the shell script will not persist when you return to the perl script. Similarly, changes to the %ENV by your perl script will not stay when it ends either. Although there are "tricks" one can do in theory.

      Can you please elaborate on this? I am not quite following you. thx

        How are you calling your shell script? Are you using system?

        system("shell.sh");

        Any changes that your shell.sh script makes to the %ENV will not stay after the system command is finished. Instead, simply have your shell.sh script echo some text that your perl script can capture when using backticks.

        my $results = `shell.sh`; if ($results =~ /Hello World/) { print "tada!"; }
        shell.sh
        echo "Hello world";