Search code examples
perl

Run system command in same context of the script itself


I have a script that runs a set of commands and it needs some env variable to be set before running one of the commands. The problem is that system command launches as a separate process, and any env variables that i set there, are not visible for the context that the script runs in. How can I overcome this?

system("set WALLET=NO");
do some perl commands; #this command needs env variable WALLET=NO to be set

Solution

  • An environment variable can be set in the program using %ENV hash

    $ENV{WALLET} = 'NO';
    run_perl_command_that_needs_ENV()
    

    The variable set in this program is seen in this program and its childrenm, not in its parent .

    How does the program "know" whether it needs to set it? That would be communicated by the shell operations executed previously, in whatever way you find most suitable. As a simple example, they can return an instruction to set the variable

    my $set_var = qx("script_that_sets_var_and_returns_flag");
    # perhaps need to process the return for the flag value
    
    if ($set_var) { 
        $ENV{WALLET} = 'NO';
        ...
    }
    

    The "backticks," used here in their operator form qx, return the stdout stream from whatever goes down in the subshell (as opposed to system, which doesn't). There are libraries which are way, way more sophisticated (or simple) in running external commands.

    Based on what actually happens in shell the return may need be processed to extract the value of the needed flag.

    Or, operations done in the shell can write a configuration file of sorts, perhaps as simple as lines with var=value pairs, and then back in the Perl script that file can be read. Then you'd need some protocol, likely rather simple-minded, for what flags there are and what they mean.

    With more detail perhaps we can provide more precise answers.