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

Hi ,

My question : how to make an environment variable visible to shell script after setting its value in a PERL script.</p.

From a KSH script, invoke a PERL script and do some database operations and retrieve a record. This record is exported using export command. Once PERL script exits, this variable is not visible to SHELL.

How can this be overcome ?

Replies are listed 'Best First'.
Re: exporting environment variable to KSH
by duff (Parson) on Mar 05, 2004 at 04:41 UTC

    It can not. This is a feature of processes in the unix model. What you can do however, is have the perl program output the results and assign that to your environment variable:

    #!/bin/ksh MYVAR=`perlprogram`
Re: exporting environment variable to KSH
by graff (Chancellor) on Mar 05, 2004 at 04:44 UTC
    You need to set up the perl script so that it prints the desired value of the variable to STDOUT (with a line feed), and then assign the output of the perl script to the variable using back-ticks, like so:
    $ FOO=`perl_script` $ export FOO
    So, if "perl_script" consists of:
    print "BAR\n"
    Then, after you have run the two shell commands above, you can see the new value:
    $ echo $FOO BAR
    There is no other way. The perl script always runs as a sub-process, and any changes to %ENV within the script are simply scrapped when that sub-process terminates -- you cannot "export" an environment variable to a parent process; you can only provide a string value, which a parent shell can then use in a variable assignment.
Re: exporting environment variable to KSH
by Anonymous Monk on Mar 05, 2004 at 05:47 UTC

    as others have pointed out, it's impossible. but you don't have to stick to simple single variable assignment. eval is your friend.

    $ eval `perl -e 'print "foo=bling bat=blam bort=boom\n"'` $ echo foo: $foo bat: $bat bort: $bort foo: bling bat: blam bort: boom
Re: exporting environment variable to KSH
by ambrus (Abbot) on Mar 05, 2004 at 15:06 UTC

    Here's the relevant entry from perldoc perlfaq8:

    I {changed directory, modified my environment} in a perl script. How come the change disappeared when I exited the script? How do I get my changes to be visible?

    Unix

    In the strictest sense, it can't be done--the script executes as a different process from the shell it was started from. Changes to a process are not reflected in its parent--only in any children created after the change. There is shell magic that may allow you to fake it by eval()ing the script's output in your shell; check out the comp.unix.questions FAQ for details.

    See also the perlmonks faq How can I change the environment from within my Perl script?.