简体   繁体   中英

Environment variables in perl

I seem to be able to access environment variables in perl just by doing:

use Env;
print ${PATH};

Is this expected behaviour?

The Env docs say you need to do $ENV{PATH} .

The Env says

Perl maintains environment variables in a special hash named %ENV . For when this access method is inconvenient, the Perl module Env allows environment variables to be treated as scalar or array variables.

So yes, this is legitimate and the expected use of variables is $PATH , $USER , $HOME , etc.

However, this module

By default it ties all existing environment variables ( keys %ENV ) to scalars.

and I prefer to use the %ENV hash directly, rather than its tie -ed counterparts. (See the source code for the core Env module on its CPAN page .)

Yes, this is expected behavior, due to the interaction of two factors:

  1. You used the Env module, which aliases $ENV{PATH} to $PATH .

Note that $ENV{PATH} is always available in Perl. use Env just adds aliases to the contents of %ENV , it is not needed to make %ENV available:

$ perl -E 'say $ENV{LANG}'
en_US.UTF-8
  1. ${PATH} is nothing more than a more verbose way of saying $PATH . The ${...} construct (and its cousins, @{...} and %{...} ) is most frequently used for interpolation within double-quoted strings, to force Perl to recognize the entire contents of the {...} as a variable name rather than a shorter name followed by literal text, but the syntax is also usable in other contexts.

A simple demonstration of this:

$ perl -E '$foo = "bar"; say ${foo}'
bar

使用 $ENV 是 perl 中预定义的变量格式

print $ENV{PATH};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM