7

Whenever I loop over a hash by its keys, and then printing each value, I get an "use of of uninitialized value in concatenation (.) or string..." warning. Even though the hash is clearly initialized up front. The output I want is printed, but I'd still like to know why this results in a warning, especially as accessing a value directly (outside of a loop) works without warnings.

#!/usr/bin/perl
use warnings;
use strict;

my %fruit = ();
%fruit = ('Apple' => 'Green', 'Strawberry' => 'Red', 'Mango' => 'Yellow');

#works
print  "An apple is $fruit{Apple} \n";

#gives warnings
foreach my $key (%fruit)
{
  print "The color of $key is $fruit{$key} \n";
}

#also gives warnings
foreach my $key (%fruit)
{
    my $value = $fruit{$key};
    print "$value \n";
}

Consider the above code. I guess perl sees a difference between the first print and the second print. But why? Why is there a difference between retrieving the value of a hash outside of loop and retrieving the value of a has inside of a loop?

Thanks!

4

3 回答 3

17

在列表上下文中使用哈希会产生键和值。因此,该行foreach my $key (%fruit)遍历键、值、键、值......

你需要的是foreach my $key (keys %fruit).

于 2013-01-11T09:31:57.677 回答
2

应该是foreach my $key ( keys %fruits )。我认为这是你真正想要做的。

于 2013-01-11T09:46:54.197 回答
2

keysfor循环内使用。例如foreach my $key (keys %fruit)...

于 2013-01-11T09:37:17.933 回答