2

I have this Perl script:

#!/usr/bin/perl

$var = `ls -l \$ddd` ;
print $var, "\n";

And ddd is a shell variable

$ echo "$ddd"
arraytest.pl

When I execute the Perl script I get a listing of all files in the directory instead of just one file, whose file name is contained in shell variable $ddd.

Whats happening here ? Note that I am escaping $ddd in backticks in the Perl script.

3 Answers 3

5

The variable $ddd isn't set *in the shell that you invoke from your Perl script.

Ordinary shell variables are not inherited by subprocesses. Environment variables are.

If you want this to work, you'll need to do one of the following in your shell before invoking your Perl script:

ddd=arraytest.pl ; export ddd # sh

export ddd=arraytest.pl       # bash, ksh, zsh

setenv ddd arraytest.pl       # csh, tcsh

This will make the environment variable $ddd visible from your Perl script. But then it probably makes more sense to refer to it as $ENV{ddd}, rather than passing the literal string '$ddd' to the shell and letting it expand it:

$var = `ls -l $ENV{ddd}`;
Sign up to request clarification or add additional context in comments.

1 Comment

The sh variant is of course portable to any Bourne-compatible shell (including ksh etc); the export variable=value syntax is ambiguous between shells so you should avoid it unless you are specifically targeting e.g. Bash. Details at unix.stackexchange.com/questions/193095/…
3

You forgot to export ddd:

Mark each name to be passed to child processes in the environment.

So ddd is not automatically available to child processes.

3 Comments

Thanks for the posting link to the reference!
@abc: Good call on going with Keith's thoroughness, I only left my answer here for that link.
@nxadm: But it won't be in %ENV because it is a shell variable, not an environment variable until you export it. Compare ddd='pancakes';perl -e 'say $ENV{ddd}, ddd='pancakes' perl -e 'say $ENV{ddd}', and export ddd='pancakes';perl -e 'say $ENV{ddd}'.
2

The hash %ENV contains your current environment.

$var = `ls -l $ENV{ddd}`;

/edit - it works, checked, of course ddd need to be exported before running script

export ddd='arraytest.pl'
perl script.pl

4 Comments

Only if it's an environment variable -- and if it were, the original code would have worked, since it passes a literal '$ddd' to the shell, which would have expanded it.
It did not work. I tried to print $ENV{ddd} but there was no o/p.
Yes, good catch its not an environment variable. Its a shell variable. I did not export it. Is there a way to specify shell variables in backquotes in Perl ?
@abc: No, there isn't. Shell variables simply aren't visible to any process other than the shell itself.

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.