perlenvironment-variables

$ENV{$variable} in Perl


Is that any way in Perl to expand the variable by in $ENV{$variable}?

I exported "a=T" and "T=b" in a shell, and I run the Perl script in which print "$ENV{$a}\n", but nothing is printed. I want to "b" have printed. How should I do it in Perl?


Solution

  • Those environment variables should be chained you say, so

    $ENV{ $ENV{a} };
    

    Note: not $a but a, like $ENV{USER} etc. This uses the hash %ENV (see perlvar), which has the current environment, so with keys being names of environment variables.


    It is apparently of interest to use a Perl variable (for the shell variable's name) in %ENV, and not a string literal as above. In that case we need to pass that shell variable, its name or the value, to the Perl program somehow so to have it stored in a variable; can't just use it directly.

    Incidentally, one of the ways to pass a variable from shell to Perl is precisely by exporting it, what then makes it available via %ENV. However, it can also be passed as usual, via command line. Assuming the use of a Perl one-liner (common in shell scripts), we have two options for how to pass

    See this post for details, and perhaps this one for another, more involved, example.


      A comment asks how to pass variable's name (string a), not its value ($a). This doesn't seem as the best design to me; if the name of a variable for some reason need be passed around then it makes sense to store that in a variable (var="a") and pass that variable, as above.

    But if the idea is indeed to pass the name itself around, then do that instead, so either of

    perl -we'...' "a"
    perl -we'...' -s -- -shv="a"
    

    The rest is the same and %ENV uses the variable that got assigned the input.

    If a full Perl script is used (not a one-liner) then use Getopt::Long to nicely handle arugments.