Perl - 所有包含的脚本和模块中可用的全局变量?

San*_*lin 16 variables perl module global

所以假设我有一个main.pl脚本,在那个脚本中我需要声明一些变量(任何类型的变量常量或正常),并且这些变量需要通过我将从该main.pl脚本自动包含的所有脚本和模块提供.

我的意思,如果我有一个变量$myVarmain.pl,并从main.pl我需要script1.pl,script2.plscript3.pm和那些我需要访问脚本的人$myVar,你会访问特定的脚本或模块定义的任何变种.

我在网上搜索过,但我只找到了一些例子,你可以从你包含的脚本中访问变量或从模块中提取变量; 但这不是我想要的.

是不是像PHP中的关键字,您将使用global $var1, $var2等从父脚本使用变量?

任何示例,文档或文章都是可以接受的 - 基本上可以帮助我完成任何事情的任何内容都会有所帮

amo*_*mon 35

您可以使用our关键字声明全局变量:

our $var = 42;
Run Code Online (Sandbox Code Playgroud)

每个全局变量都有一个完全限定的名称,可用于从任何地方访问它.全名是包名称加上变量名称.如果您尚未在此时声明包裹,则您处于打包状态main,可以缩短为领先::.所以上面的变量有名字

$var       # inside package main
$main::var # This is most obvious
$::var     # This may be a good compromise
Run Code Online (Sandbox Code Playgroud)

如果我们使用了另一个包,前缀会改变,例如

package Foo;
our $bar = "baz";
# $Foo::bar from anywhere,
# or even $::Foo::bar or $main::Foo::bar
Run Code Online (Sandbox Code Playgroud)

如果我们想要使用没有前缀的变量,但在其他包下,我们必须将其导出.这通常通过子类化来完成Exporter,请参阅@Davids答案.但是,这只能提供来自used的包的变量,而不是相反.例如

Foo.pm:

package Foo;
use strict; use warnings;
use parent 'Exporter'; # imports and subclasses Exporter

our $var = 42;
our $not_exported = "don't look at me";

our @EXPORT = qw($var); # put stuff here you want to export
# put vars into @EXPORT_OK that will be exported on request

1;
Run Code Online (Sandbox Code Playgroud)

script.pl:

#!/usr/bin/perl
# this is implicitly package main
use Foo; # imports $var

print "var = $var\n"; # access the variable without prefix
print "$Foo::not_exported\n"; # access non-exported var with full name
Run Code Online (Sandbox Code Playgroud)

词法变量(声明为my)不具有全局唯一名称,并且不能在其静态范围之外访问.它们也不能用Exporter.


Dav*_*vid 5

最简单的方法是创建自己的模块.因此,例如,如果我想要全局访问变量$foo and $bar,那么我可以创建一个模块,如下所示:

# file:  MyVars.pm
package MyVars;

$foo = 12;
$bar = 117.8;

1;
Run Code Online (Sandbox Code Playgroud)

然后我可以使用任何使用MyVars模块的perl脚本访问这些变量:

# file:  printvars.pl
use MyVars;

print "foo = $MyVars::foo\nbar = $MyVars::bar\n";
Run Code Online (Sandbox Code Playgroud)

输出:

foo = 12
bar = 117.8
Run Code Online (Sandbox Code Playgroud)