总结一下:
这是我放入 /tmp 中的代码的极其简化的提取,以说明我的问题:
主脚本(/tmp/nonstdtest.pl):
#!/usr/bin/perl
use lib '/tmp';
use TEST;
use Data::Dumper;
my %nonstd;
tNumber(\%nonstd);
print Dumper(\%nonstd);
软件包(/tmp/TEST.pm):
package TEST;
use strict;
use warnings;
our @ISA= qw( Exporter );
our @EXPORT_OK = qw( tNumber );
our @EXPORT = qw( tNumber );
sub tNumber {
my $nonstd = shift;
$nonstd = %$nonstd;
$nonstd{'example'} = 'test_here';
}
问题,输出是:
Global symbol "%nonstd" requires explicit package name at /tmp/TEST.pm line 15.
Compilation failed in require at /tmp/nonstdtest.pl line 5.
BEGIN failed--compilation aborted at /tmp/nonstdtest.pl line 5.
问题:如何使用包中定义的子例程修改 %nonstd (在主脚本中定义)的内容?
我尝试在没有包的情况下(在同一脚本内)执行此操作,并且它运行正常(只要我在子例程中保留具有相同名称的哈希值),所以我在这里做错了:=(
我在上面的示例中期望的结果只是让 %nonstd 填充 1 个键/值对(示例/test_here)
提前致谢,
您的问题是一个拼写错误:
$nonstd{'example'} = 'test_here';
试图从
%nonstd
获取密钥,但您声明了 my $nonstd
,这是一个标量。它们不是同一个变量。它违反了 strict pragma,这就是我们使用 strict 的原因,因为它可以帮助我们发现拼写错误。
应该是:
$nonstd->{'example'} = 'test_here';
但这也是错误的:
$nonstd = %$nonstd;
您已经有了哈希引用,但现在您将其替换为哈希的大小,这就是将哈希放入标量上下文中时得到的结果。所以实际上,您已经破坏了哈希引用。只需删除这一行即可。
但是,当我通过此更正运行此代码时,我收到另一个错误:
Undefined subroutine &main::tNumber called at non.pl line 10.