在Perl程序中访问shell变量 [英] Accessing shell variable in a Perl program

查看:206
本文介绍了在Perl程序中访问shell变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Perl脚本:

I have this Perl script:

#!/usr/bin/perl

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

而ddd是一个shell变量

And ddd is a shell variable

$ echo "$ddd"
arraytest.pl

当我执行Perl脚本时,我得到目录中所有文件的列表,而不只是一个文件名,该文件名包含在shell变量$ ddd中.

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.

这是怎么回事?请注意,我在Perl脚本中的反引号中将$ ddd转义.

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

推荐答案

在您从Perl脚本调用的shell中没有设置变量$ddd.

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

普通的shell变量不被子进程继承.环境变量是.

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

如果您希望此方法有效,则需要在Shell中执行以下操作之一,然后调用Perl脚本:

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

这将使环境变量$ddd在您的Perl脚本中可见.但是,将它称为$ENV{ddd}而不是将文字字符串'$ddd'传递到外壳并让其扩展它可能更有意义:

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

这篇关于在Perl程序中访问shell变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆