Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

linux - Accessing shell variable in a Perl program

I have this Perl script:

#!/usr/bin/perl

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}`;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...