2

I need to access the value of a shell variable in a perl script. I can get it if it's an environment variable but not a regular ole shell variable. Consider

% set AAA=Avalue
% setenv BBB=Bvalue
% echo $AAA
Avalue
% echo $BBB
Bvalue

So far, so good. Now, here's a perl script to read them...

#!/usr/bin/env perl
use strict;

print "AAA: ".$ENV{AAA}."\n";
print "BBB: ".$ENV{BBB}."\n";

exit;

When I run it, I get...

AAA:
BBB: Bvalue

How can I get the value of AAA from inside the perl script ?

Thanks in Advance

5
  • Oh, forgot to say, default interpreter is c-shell Commented Feb 6, 2018 at 22:03
  • 2
    I'm not familiar with csh, but my guess would be that set only sets environment variables for the current shell, and not for sub-shells. You're obviously setting BBB in a different way than you've shown here, or else your example wouldn't work. Commented Feb 6, 2018 at 22:11
  • Yes, I 'setenv BBB". edited/fixed. Thanks. (I should have cut/paste) Commented Feb 6, 2018 at 22:47
  • 2
    Regular ole shell variables are not inherited by their child processes. Commented Feb 6, 2018 at 22:50
  • What do you expect from perl -e'$AAA="Avalue"; $ENV{BBB}="Bvalue"; system("script.pl");? As you should be realizing now, your request makes no sense. Commented Feb 7, 2018 at 0:23

2 Answers 2

3

You are not getting the value of AAA variable because AAA is local env variable where as BBB is exported variable.

Exported variables are carried into the environment of processes started by the shell that exported them, while non-exported variables are local to the current process only.

Example:

$ set AAA=123
$ csh
$ echo $AAA
AAA: Undefined variable.
$ exit

$ setenv BBB 456
$ csh
$ echo $BBB
456
Sign up to request clarification or add additional context in comments.

2 Comments

So it's a scoping thing. Fortunately, the perl script is being called by a sourced shell script, so I should be able to set the variables I need as environment variables, then run the perl. Thanks.
Re "So it's a scoping thing", No, not really. They are different. It's like my $x; vs $ENV{x} in Perl.
1

A process doesn't have access to another process's memory, much less its variables. If you want your Perl script to have a value, you will need to pass the value to it somehow (e.g. via its environment).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.