Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}.

like image 363
CJ7 Avatar asked Aug 22 '17 04:08

CJ7


People also ask

How do you set environment variables in Perl?

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.

How many types of variables are there in Perl?

Perl has three main variable types: scalars, arrays, and hashes.

What is $_ in Perl script?

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"; }

How do I set an environment variable?

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.


3 Answers

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.)

like image 127
zdim Avatar answered Oct 18 '22 09:10

zdim


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
like image 33
Dave Sherohman Avatar answered Oct 18 '22 09:10

Dave Sherohman


Use $ENV is predefined variable format in perl

print $ENV{PATH};
like image 32
Prabhakaran Ravichandran Avatar answered Oct 18 '22 11:10

Prabhakaran Ravichandran