Perl:如何通过要求脚本中的要求脚本提供变量 [英] Perl: how to make variables from requiring script available in required script
问题描述
示例
out.pl:
(my|our|local|global|whatever???) var = "test";
require("inside.pm");
inside.pm:
inside.pm:
print $var;
我不想使用软件包-它压倒了我的需求:) 谢谢!
I don't want to use packages - it's overwhelming my needs :) thanks!
推荐答案
它将与our
一起使用.
$ cat out.pl
our $var = "test";
require("inside.pm");
$ cat inside.pm
print "Testing...\n";
print "$var\n";
$ perl out.pl
Testing...
test
之所以起作用,是因为our
使$var
成为全局变量,并且inside.pm
在定义了$var
的作用域中执行.不确定是否建议使用该技术,但这仍然是一个有趣的问题!
This works because our
makes $var
global, and inside.pm
is being executed in the scope with $var
defined. Not sure it is recommended technique, but it is an interesting question nevertheless!
编辑:需要根据评论来澄清(好的补丁)答案:
EDIT: Need to clarify (okay patch) the answer based on a comment:
来自有关Perl函数our
的文档:
From the documentation on the Perl function our
:
our
将简单名称与当前包中的包(读取:全局)变量相关联,以在当前词法范围内使用.换句话说,our
具有与my
或state
相同的作用域规则,但不一定创建变量.
our
associates a simple name with a package (read: global) variable in the current package, for use within the current lexical scope. In other words,our
has the same scoping rules asmy
orstate
, but does not necessarily create a variable.
因此,使用our
,我们将使用当前软件包(此处可能是main
)获得$var
,并且可以在其范围内使用它.实际上,它是您需要输入的文件中的代码的全局".
So using our
, we get $var
with the current package (here probably main
) and we can use it in its scope. In effect it is then "global" to the code in the file you are requiring-in.
引入了 true全局,而没有our
,因为变量默认为global.但是我不认识会推荐他们的人.
A true global is introduced without the our
, because variables default to global. But I don't know anyone that would recommend them.
这篇关于Perl:如何通过要求脚本中的要求脚本提供变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!