On Tue, Mar 19, 2002 at 10:46:04AM +1100, [EMAIL PROTECTED] wrote:
> 
> In an attempt to stimulate non-golf threads:
> 
> .. Has anybody done any really interesting Perl "hacks" that they are
> proud of?


Yeah, I do actually. Recently I was writing a program that needed
to (shell) source a file, to get some environment variables set,
and use those variables in further calculations.

I could of course have written a shell wrapper that sourced the file,
then started my program. But I decided I just wanted a single program.

To source a shell file, one cannot use 'system' - that would start
a child process, and setting the environment in the child is pointless.
So, I decided to use a trick, a double exec. First I exec a shell
that is sourcing the file with the environment variables, then I
exec the original program - with a special argument to indicate the
variables have been set.

The relevant part of said program follows.


Abigail



my $ENVIRONMENT = "/some/file/somewhere";

if (@ARGV && $ARGV [0] eq '--sourced_environment') {
    shift;
}
else {
    if (-f $ENVIRONMENT) {  
        #
        # Now we perform a double exec. The first exec gives us a shell,
        # allowing us the source the file with the environment variables.
        # Then, from within the shell we re-exec ourself - but with an
        # argument that will prevent us from going into infinite recursion.
        #
        # We cannot do a 'system "source $ENVIRONMENT"', because
        # environment variables are not propagated to the parent.
        #
        # Note the required trickery to do the appropriate shell quoting
        # when passing @ARGV back to ourselves.
        #

        @ARGV = map {s/'/'"'"'/g; "'$_'"} @ARGV;

        exec << "        --";
            source '$ENVIRONMENT'
            exec    $0  --sourced_environment @ARGV;
        --
        die  "This should never happen.";
    }
}

Reply via email to