knsridhar has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks

I have a situation where i have to set shell environment variables within perl script and invoke shell command which uses this environment variable using system() function.

I am able to set the environment variable from perl, but when i try to access it through system() function, it doesnt print anything. Can anyone explain me and suggest me a solution

Thanks

Replies are listed 'Best First'.
Re: Setting Environment variables in Perl
by Zaxo (Archbishop) on Sep 12, 2005 at 06:35 UTC

    It works for me:

    $ echo $FOO $ cat >foo.sh #!/bin/sh echo $FOO $ chmod 755 foo.sh $ cat >foo.pl #!/usr/bin/perl $ENV{'FOO'} = 'bar'; system './foo.sh'; $ perl foo.pl # corrected, Hue-Bond++ bar $
    What does your code look like?

    After Compline,
    Zaxo

      Just a little note:

      $ cat >foo.pl #!/usr/bin/perl $ENV{'FOO'} = 'bar'; system './foo.sh'; $ perl foo.sh

      I think you mean perl foo.pl.

      --
      David Serrano

      Hi,

      It works because $ENV gives you access to your current environment and child environments. Once your foo.pl ends your FOO will be gone.

      Try executing foo.sh once more after foo.pl finishes. You'll see the value of FOO being empty.

      --
      if ( 1 ) { $postman->ring() for (1..2); }

        The OP said:

        I have a situation where i have to set shell environment variables within perl script and invoke shell command which uses this environment variable using system() function.

        So the commands are being run from within the Perl script using system(). They will be children of the Perl and will inherit it's environment.

        Cheers,
        R.

        Pereant, qui ante nos nostra dixerunt!
        Yes, a process can never change the environment variables of a parent process, which is what would happen if FOO was still there when the script finished (a perl script runs in a child process from your shell). /Hacker
Re: Setting Environment variables in Perl
by anthski (Scribe) on Sep 12, 2005 at 07:05 UTC
    Does it show up in your env listing when you execute the system call?

    For example.

    #!/usr/bin/perl use warnings; use strict; $ENV{'ANTH'} = "bignuts"; system('/bin/env');

    when run like

    # ./env.pl

    will output, amongst other things:

    ANTH=bignuts

    If you do this (swapping the environment variable name and value as desired), does it show up when you execute this code?

    cheers,
    Anth

Re: Setting Environment variables in Perl
by davidrw (Prior) on Sep 12, 2005 at 12:37 UTC