Perl: import shell variable

324 views Asked by At

In shell, I had sourced .cshrc file which contains some defined variables like user name.

I need to pass these variables to a certain Perl script.

For example in shell terminal, I typed

>echo $user

The output is >esaad

Then in Perl, to read $user variable, I tried:

system("echo $user")

Also tried this command:

my $userName = system( echo $ENV{user} );

but Perl asked for $user initialization as Perl variable not Shell one.

How I could read this variable?

2

There are 2 answers

0
Alex G On BEST ANSWER

You can:

print $ENV{'user'}

the reason your system call doesn't work is that system open a new shell that doesn't source .cshrc read this answer for more information

1
Lye Heng Foo On

Either use Perl built-in system variable $ENV:

print $ENV{'user'}

Or use backslash to escape the variable $user. Perl will interpret for $user variable defined inside the Perl program without the backslash. With backslash, "echo $user" is passed as system call.

system("echo \$user")