How to Set a Variable Used in a Perl Script as Environment Variable

Can we set a variable used in a Perl script as environment variable?

If you want to affect the environment of your process or your child processes, just use the %ENV hash:

$ENV{CVSROOT}='<cvs>';

If you want to affect the environment of your parent process, you can't. At least not without cooperation of the parent process. The standard process is to emit a shell script and have the parent process execute that shell script:

#!/usr/bin/perl -w
print 'export CVSROOT=<cvs>';

... and call that script from the shell (script) as:

eval `myscript.pl`

using environment variable in the perl script

$GATE in a double quoted string will be considered a Perl variable. If you want to use an environment variable, you can use the %ENV hash:

system ("bsub xyz +OPTIONS_GATE=$ENV{GATE}")

Alternatively, you can escape the dollar sign so Perl does not treat $GATE as a Perl variable:

system ("bsub xyz +OPTIONS_GATE=\$GATE")

Or use a single quoted string, which does not interpolate variables:

system ('bsub xyz +OPTIONS_GATE=$GATE')

Note that if you had used

use strict;
use warnings;

It would have told you about this error. strict would have said:

Global symbol "$GATE" requires explicit package name
Execution of script.pl aborted due to compilation errors.

And warnings would have said:

Name "main::GATE" used only once: possible typo at script.pl line 12.
Use of uninitialized value $GATE in string at script.pl line 12.

When you do not use use strict; use warnings; your errors are not removed, they are only hidden from you, so that they are harder to find. Therefore, always use these two pragmas.

How do I set an environment variable in Perl?

You can do it like this:

$ENV{HOME} = 'something different';

But please note that this will only have an effect within the rest of your script. When your script exits, the calling shell will not see any changes.

As perldoc -v %ENV says:

%ENV The hash %ENV contains your current environment. Setting a value in "ENV" changes the environment for any child processes you subsequently "fork()" off.



Related Topics



Leave a reply



Submit