有些人可以解释如何将HASH从模块传递给main。我已经阅读了How to share/export a global variable between two different perl scripts?这样的帖子,并了解其背后的基本概念,但这有点不同,我找不到任何例子。
如果从main调用此模块,则该模块如何工作,但是如何将散列传递给main,以便我可以在那里打印,而不是从模块打印。或者我可以将键值写入文件或其他内容。
package My::Module;
use strict;
use warnings;
use Exporter;
our @ISA = 'Exporter';
our @EXPORT = qw(get_proc_info);
sub get_proc_info
{
my %processor;
Win32::SystemInfo::ProcessorInfo(%processor);
for (my $i=0;$i<$processor{NumProcessors};$i++)
{
print "Processor $i\n";
print "Processor Name: " . $processor{"Processor$i"}{ProcessorName} . "\n";
print "Processor Info: " . $processor{"Processor$i"}{Identifier} . "\n";
print "Processor Speed: " . $processor{"Processor$i"}{MHZ} . "MHz\n\n";
}
}
答案 0 :(得分:3)
导出变量是一种不好的做法。但是,您始终可以导出返回变量内容的子项:
#!/usr/bin/perl
use warnings;
use strict;
{ package HashExport;
my %hash = ( key => 'value' );
sub get_hash {
return %hash
}
}
use Data::Dumper;
my %imported = HashExport::get_hash();
print Dumper \%imported;
答案 1 :(得分:1)
返回对它的引用。
模块:
package My::Module;
use strict;
use warnings;
use Exporter qw( import );
use Win32::SystemInfo qw( );
our @EXPORT_OK = qw( get_processors );
sub get_processors {
my %processors;
Win32::SystemInfo::ProcessorInfo(%processors);
return \%processors;
}
1;
来电者:
use My::Module qw( get_processors );
my $processors = get_processors();
for my $i (0 .. $processors->{NumProcessors}-1)
my $processor = $processors->{"Processor$i"};
print "Processor $i\n";
print "Processor Name: $processor->{ProcessorName}\n";
print "Processor Info: $processor->{Identifier}\n";
print "Processor Speed: $processor->{MHZ} MHz\n";
print "\n";
}
以上已经&#34;修复&#34;一些Win32::SystemInfo::ProcessorInfo
奇怪的接口。以下修正了它:
模块:
package My::Module;
use strict;
use warnings;
use Exporter qw( import );
use Win32::SystemInfo qw( );
our @EXPORT_OK = qw( get_processors );
sub get_processors {
my %processors;
Win32::SystemInfo::ProcessorInfo(%processors);
return
map { $processors{"Processor$_"} }
0 .. $processors{NumProcessors}-1;
}
1;
来电者:
use My::Module qw( get_processors );
my @processors = get_processors();
for my $i (0..$#processors)
my $processor = $processors[$i];
print "Processor $i\n";
print "Processor Name: $processor->{ProcessorName}\n";
print "Processor Info: $processor->{Identifier}\n";
print "Processor Speed: $processor->{MHZ} MHz\n";
print "\n";
}
答案 2 :(得分:1)
这取决于你正在尝试做什么
您可以使用Exporter
导出任何包标识符。它恰好被命名为不需要前导符号的子程序,并且始终是包标识符
我可以像这样创建一个全局可访问的哈希
package MyStuff;
use strict;
use warnings 'all';
use Exporter 'import';
our @EXPORT_OK = qw/ %Data /;
our %Data = (
a => 1,
b => 2,
c => 3,
);
1;
然后像这样导入和使用
use strict;
use warnings 'all';
use MyStuff '%Data';
use Data::Dump;
dd \%Data;
{ a => 1, b => 2, c => 3 }
但是任何类型的全局可变值都会让您在远距离错误的各种操作中打开。编写一个返回对值的引用的全局子例程的替代方法实际上并不是更好