开发者

Variable not seen as defined in foreach of a hash

开发者 https://www.devze.com 2023-04-11 04:35 出处:网络
my $crazy_hash = { \'One\' => 1, \'Two\' => 1, \'Three\' =>开发者_StackOverflow中文版 1, };
my $crazy_hash = {

  'One' => 1,

  'Two' => 1,

  'Three' =>开发者_StackOverflow中文版 1,

};


 foreach my $num (keys %crazy_hash) {
      #DoSomething    
  }

The error I get is:

Global symbol "%crazy_hash" requires explicit package name at blah line blah

If I do my %crazy_hash and define it within the loop, it works. Why doesn't it work as is?


You have not defined a hash called %crazy_hash, you have defined a scalar $crazy_hash which contains a reference to a hash.

You probably mean this:

my %crazy_hash = ( One => 1, ...

... or access the keys with keys %{$crazy_hash} like others have suggested; then you will need to use $crazy_hash->{key} rather than $crazy_hash{key} to access a value. Read perlreftut if you need to understand references.


$crazy_hash is a reference to an anonymous hash. Prior to 5.14, you need to dereference the reference for keys to work:

for my $num (keys %{$crazy_hash}) {

Starting with 5.14:

Starting with Perl 5.14, keys can take a scalar EXPR, which must contain a reference to an unblessed hash or array. The argument will be dereferenced automatically. This aspect of keys is considered highly experimental. The exact behaviour may change in a future version of Perl.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号