how to setenv in perl script

Why command below doesn't work? Even I try qx, it also doesn't work....

#!/usr/bin/perl -w

system "setenv P Hello";
print "\nEnvironment Variable P = $ENV{P}\n\n" ;

Pls advice.

Who is Participating?
wilcoxonConnect With a Mentor Commented:
Just set the $ENV{P} value directly.

$ENV{P} = 'Hello';
print "\nEnvironment Variable P = $ENV{P}\n\n";
To amplify a bit on what Wilcoxon said...

Environment variables are inherited by sub-processes but do not propagate up to parent processes. The "system" operator and qx operators both create subprocesses to run the command you specify.

The scope of $ENV{P} is the current process and any future children -- it will not have an effect on the shell or other process from which you invoked the Perl script.
fl78Author Commented:
I tried this:

$ENV{P} = 'Hello';
print "\nEnvironment Variable P = $ENV{P}\n\n";

the screen able to print:

Environment Variable P = Hello

but when I do echo $P on the shell, it prompted to me:

P: Undefined variable.

How to do it in perl so that when echo $P being invoked, it will show me Hello. Pls advice.
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

I'm not sure what you mean.  These should all work.

$ENV{P} = 'Hello';
system 'echo $P';
system '/bin/sh'; # not sure if this will start an interactive shell or not (haven't tried)

As jmcq said, setting "$ENV{P}" within perl will cause any child processes to inherit $P.  As far as I know there is no way to make a perl %ENV variable persist past the perl process or to make the parent inherit the variable setting.
In order for the action of the perl script to effect a change in an environment variable in the invoking shell, you would have to invoke the perl script in such a way as it's output would be evaluated by the shell and have the perl script output shell commands that, when evaluated by the shell, change the value of the environment variable.

Perl script, let's call it "changeenvP":

print "setenv P Hello\n"

Invoked from shell (assumed to be a C-shell variant because you were using 'setenv' as):

eval `changeenvP`


This is no different than the requirement to use the . or 'source' command to evaluate a shell script that attempts to change environment variables.
I think the problem is that you are not invoking the shell again after making the changes
After running the pgm just do this
if bash
. ~/cshrc

if csh or tcsh
source .~/cshrc

hope that helps
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.