When you use system or backticks or qx{}, the command is executed in a newly spawned shell, so setting an environment variable using one of these methods will not reflect to the calling process. Consider it to be equivalent to (I used $$ to show that it is the prompt of the sub-shell)

$ export A=1 $ echo $A 1 $ bash $$ echo $A 1 $$ export A=2 $$ echo $A 2 $$ exit $ echo $A 1

So, those three are out.

The case of %ENV is way more interesting, as it involves scope and timing. Lets start with simple examples:

$ echo $A;perl -wE'say $ENV{A};$ENV{A}=2;say$ENV{A}';echo $A 1 1 2 1 $ perl -wE'say $ENV{A};qx{echo \$A};$ENV{A}="B";say $ENV{A };qx{echo \$A};' 1 B

You can observe that the proces spawned with the first qx uses the original value stored in $A, and the second invocation uses the changed value, as you expect (if I read your question correctly), so no surprises there.

What will complicate matters is if those %ENV values are used in the startup phase of a module that you use. This implies that the value is used before you change its value. In that case, you should do something like

BEGIN { $ENV{test} = "B"; } use My::Module; # Which initializes with $ENV{test}

Now the environment is set before it is seen by the module.

HTH


Enjoy, Have FUN! H.Merijn

In reply to Re: setenv in perl by Tux
in thread setenv in perl by dideod.yang

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.