in reply to YES you can! Re: setenv in perl
in thread setenv in perl

Yes exec doesn't spawn a child process but hands over control to another "executable" on the same level, which never returns.

Your trick only works interactively because you need to exec a NEW follow up shell, waiting for human input.

This means this illusion won't work in a non interactive script. All code after the exec will be ignored.

Replies are listed 'Best First'.
Re^2: NO you can't ! Re: setenv in perl
by bliako (Abbot) on Jul 09, 2018 at 20:46 UTC

    On a more serious node, the exec() is a safe (Edit: not safe as in safety and security) way to achieve what the question asked as my use-case demonstrated. It is true that unless one executes the "trick" from an interactive shell any command past that exec will not run as KurtZ whines rightly points out. For example as a cron job.

    I don't see it as a "trick" because this is what exec() was intended to do in the first place. It is not exploiting any of its features=bugs, it is not using it in a heads-down-feet-up kind of way.

    And definetely the result is not an illusion because it's there. You get your environment modified albeit within a brand new shell which inherits from the parent shell. It inherits env variables and even opened file descriptors. For example:

    exec 3> /tmp/out echo 'before exec' >&3 exec env2.pl echo 'after exec' >&3 exec 3>&- cat /tmp/out before exec after exec

    So, not a trick, not an illusion but limited (and what isn't) to interactive shells.

    For non-interactive use, e.g. a cron-job one can go with corion's Re: setenv in perl. And if only 1 env-variable needs to be set up, then the eval can be avoided by using:

    export test=`perl -e 'print 'TURE'`

    Lastly, if the scenario is to run a shell command which reads data from the environment and having a perl script to calculate this data and export it to the environment then why not let perl calculate AND spawn the command because any system() call inherits perl's environment vars, like so:

    #!/usr/bin/env perl $ENV{test} = 'TURE'; # calculate my @cmd = ('command-exec', 'args'); system(@cmd); # spawn # simple demo: system('echo $test'); # prints what

    bw, bliako

      The same can be achieved with a shell alias or function calling a Perl function and exporting the returned variable value pairs.

      with less code and side effects

Re^2: NO you can't ! Re: setenv in perl
by bliako (Abbot) on Jul 09, 2018 at 17:26 UTC

    Nope! Not in a Quantum Computer running UNIX. There, in a parallel universe my "trick"'s "illusion" will warp into reality.

      That's kind of Schrödinger's BS, right?

      You need to taste it to find out it's not chocolate! ;P

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

        I was undecided but then I did come to a conclus... oops someone did an exec() on me ...