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}
.
If you need to set an environment variable to be seen by another Perl module that you're importing, then you need to do so in a BEGIN block. Without putting it in a BEGIN block, your script will see the environment variable, but DBI will have already been imported before you set the environment variable.
Perl has three main variable types: scalars, arrays, and hashes.
The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }
On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.
The Env says
Perl maintains environment variables in a special hash named
%ENV
. For when this access method is inconvenient, the Perl moduleEnv
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:
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
${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
Use $ENV is predefined variable format in perl
print $ENV{PATH};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With