3

I understand shell variables are local to the current shell while environment variables (the exported ones) are passed onto child processes forked by the shell.

When I run a Perl one-liner within double quotes I can access the (local) shell variable from the forked perl process:

$ FOO=bar
$ perl -we "print qx'echo $FOO'"
bar

Why is that?

jreisinger
  • 1,493
  • 1
  • 10
  • 21

2 Answers2

5

It's because of shell variable interpolation in double-quoted strings.

The $FOO variable is evaluated in the parent shell - in which $FOO has value bar - and interpolated into the quoted string.

Therefore the perl code you are actually running is:

print qx'echo bar'
e.dan
  • 7,275
  • 1
  • 26
  • 29
  • [Here](http://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash) is a more detailed explanation. – jreisinger Aug 02 '16 at 09:22
4

This is because your shell translates the content of $FOO before it is submitted to Perl.

If you want to use this $FOO from your Perl environment, do this:

perl -we "print qx'echo \$FOO'"

The shell should translate \$ in to $ before passing it away.

J. Chomel
  • 8,193
  • 15
  • 41
  • 69