Accessing shell variable in a Perl program

一曲冷凌霜 提交于 2020-11-24 17:25:27

问题


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.


回答1:


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



回答2:


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:


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


来源:https://stackoverflow.com/questions/6964536/accessing-shell-variable-in-a-perl-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!