如何在两个不同的perl脚本之间共享或导出全局变量。
情况是这样的:
first.pl
#!/usr/bin/perl
use strict;
our (@a, @b);
.........
second.pl
#!/usr/bin/perl
use strict;
require first.pl;
我想使用在first.pl中声明的全局变量(@a
,@b
另外,假设第二个perl文件中有一个变量与第一个perl文件中的变量相同。但是我想使用第一个文件的变量。如何做到这一点?
发布于 2010-12-29 01:58:05
通常,当您处理多个文件,并在它们之间导入变量或子例程时,您会发现,随着项目的增长,所需的文件最终会变得有点复杂。这是因为所有东西都共享一个公共名称空间,但一些变量在一些文件中声明,而另一些文件中没有声明。
在Perl中解决这个问题的通常方法是创建模块,然后从这些模块导入。在这种情况下:
#!/usr/bin/perl
package My::Module; # saved as My/Module.pm
use strict;
use warnings;
use Exporter;
our @ISA = 'Exporter';
our @EXPORT = qw(@a @b);
our (@a, @b);
@a = 1..3;
@b = "a".."c";
然后使用该模块:
#!/usr/bin/perl
use strict;
use warnings;
use My::Module; # imports / declares the two variables
print @a;
print @b;
这行use
实际上意味着:
BEGIN {
require "My/Module.pm";
My::Module->import();
}
import
方法来自Exporter
。当它被调用时,它会将@EXPORT
数组中的变量导出到调用代码中。
发布于 2010-12-28 13:55:22
它们将共享全局变量,是的。你觉得这有什么问题吗?
示例:
first.pl:
#!/usr/bin/perl
use strict;
use warnings;
our (@a, @b);
@a = 1..3;
@b = "a".."c";
second.pl:
#!/usr/bin/perl
use strict;
use warnings;
require "first.pl";
our (@a,@b);
print @a;
print @b;
给予:
$ perl second.pl
123abc
发布于 2010-12-28 13:57:48
不能使用打包并导出变量吗?
https://stackoverflow.com/questions/4543934
复制相似问题