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
G++ Searches /Lib/../Lib/, Then /Lib/
Python Socket.Error: [Errno 13] Permission Denied
Linking a C Library and Its Supporting Library in Swift (Linux)
Netfilter-Like Kernel Module to Get Source and Destination Address
How to Copy Folder with Files to Another Folder in Unix/Linux
When to Use Pipes VS When to Use Shared Memory
Need Explanations for Linux Bash Builtin Exec Command Behavior
Examining Berkeley Db Files from the Cli
Finding Executable Files Using Ls and Grep
Shell-Init: Error Retrieving Current Directory: Getcwd -- the Usual Fixes Do Not Wor
Bash Output Stream Write to a File
How to Use Grep to Match But Without Printing the Matches
Should %Rsp Be Aligned to 16-Byte Boundary Before Calling a Function in Nasm
Command Substitution Within Sed Expression
How to Force Cp to Overwrite Without Confirmation
Linux Shell to Restrict Sftp Users to Their Home Directories