【问题标题】:Perl - Global symbol requires explicit package namePerl - 全局符号需要明确的包名
【发布时间】:2016-08-19 16:49:18
【问题描述】:

我正在调用一个 perl 子例程

&ProcessInput($line, \%txcountershash, \%txhash);

我有这个定义:

sub ProcessInput() {    
my $word;
my $counterkey;   
my $line = $_[0];
my $countershash = $_[1];
my $outputhash = $_[2];  

# remove all the blanks from the line
$line =~ s/\s+//g;  

my ($port,$counter,$value,$datetime) = split('\|',$line,4);

my $counterdesc = $countershash{$counter};

导致问题的行是最后一行。它说全局符号 %countershash 需要明确的包名。我不确定为什么它给了我错误。否则没有任何问题,如果我注释掉脚本运行的那一行。哈希被设置为键的错误代码和作为值的描述。我正在尝试获取 $countershash 中特定键的值,以便可以将错误描述添加到输出哈希中。

【问题讨论】:

  • 另外,不再需要在函数调用的前面加上&
  • 对不起。澄清。它在抱怨 %countershash。我意识到我错误地删除了定义 $counter 的行
  • 叫它$countershash->{$counter}
  • Perl 抱怨一个名为 %countershash 的散列,您没有定义它,而是有一个名为 $countershash 的散列引用。
  • 啊。谢谢。这是有道理的。

标签: perl


【解决方案1】:

问题在于取消引用。您应该取消引用子例程内的哈希

my $counterdesc = $countershash->{$counter};

-> 这称为arrow operator,用于尊重数组和散列。

【讨论】:

  • 请不要向人们展示那种可怕的语法。从哈希引用中获取元素的推荐方法是使用->。所以,my $counterdesc = $counterhash->{$counter};.
  • @DaveCross 感谢您编辑的评论帖子。 :)
【解决方案2】:

代码$counterhash{$counter} 的意思是“在哈希%counterhash 中查找密钥$counter”。你没有一个名为%counterhash 的散列,你在一个名为$counterhash 的标量变量中有一个散列引用。 %counterhash$counterhash 是两个完全不同的变量。

为了在哈希引用中查找元素,您需要使用不同的语法。

my $counterdesc = $countershash->{$counter};

请不要使用另一个答案中使用的 $$countershash{$counter} 语法(以前)。这只会让需要在六个月内维护您的代码的人(很可能是您)感到困惑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多