Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setup Environment variable using perl

I am trying to set environment variable using Perl. It should export this variable outside (in current shell) not just in the script.

I tried:

`setenv X1 /p/fsd`

system("setenv X1 /p/fsd") == 0 or die "failed:$?"

system command "setenv X1 /p/fsd" failed: -1

$ENV{"X1"} = "/p/fsd"; 

Nothing seems to be working.

If it matters i am using TCSH.

like image 735
user1793023 Avatar asked Nov 15 '12 00:11

user1793023


People also ask

How do you set environment variables in Perl?

For example, to determine the setting of your "PATH" environment variable, you can write a line of Perl code like this: $path = $ENV{'PATH'}; As you may remember, "%ENV" is a special hash in Perl that contains the value of all your environment variables.

How do I declare a variable in Perl?

Perl variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

What is use ENV in Perl?

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

What is @_ and $_ in Perl?

$_ - The default input and pattern-searching space. @_ - Within a subroutine the array @_ contains the parameters passed to that subroutine. $" - When an array or an array slice is interpolated into a double-quoted string or a similar context such as /.../ , its elements are separated by this value.


2 Answers

$ENV{"X1"} = "/p/fsd"; 

is the right way.

Test in perlconsole :

Perl> $ENV{X1} = "/p/fsd";
/p/fsd

Perl> system('echo $X1');
/p/fsd
0

NOTE

  • the single quotes (or backslashing) is required on echo $X1 to prevent perl to interpolate it itself.
  • you can't change ENV of parent shell, see http://www.perlmonks.org/?node_id=684685
like image 185
Gilles Quenot Avatar answered Sep 29 '22 22:09

Gilles Quenot


Equally important to know how to set an env variable is how to delete it:

delete $ENV{"X1"};

This will delete the environment variable for the perl process and any children processes. But the environment variable will still be set for the parent process.

like image 39
jcarballo Avatar answered Sep 29 '22 22:09

jcarballo