Clever. Here's what happens.

When you run Perl with exec, it replaces the shell in the same process. This is the key; just running Perl as it is usually done will not have this effect, which is why you got so many "It can't be done" responses. Because environment variables live in a process, the Perl script sees the same environment the shell did.

When you then exec the shell after modifying the environment, the new copy of the shell, still running in the same process, sees those modifications.

I do have a couple observations to add.

This approach only works if you have control over how your Perl script is run.

Unless the Perl script is in the PATH, I found I needed to explicitly specify the directory: ./env.pl

If you do it this way, you do not need to use Inline::C. Simply modifying %ENV will work:

#!/usr/bin/env perl use 5.008; use strict; use warnings; $ENV{test} = 'TURE'; exec $ENV{SHELL} or die "Failed to exec shell '$ENV{SHELL}'\n";

works just as well:

$ echo "PID=$$; test='$test'" PID=87533; test='' $ exec ./exec.pl $ echo "PID=$$; test='$test'" PID=87533; test='TURE'

In reply to Re: YES you can! Re: setenv in perl by Anonymous Monk
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.