Perl - 为什么通过键遍历哈希然后打印每个值会导致未初始化的警告?

Gx1*_*TDa 7 perl hash foreach

每当我通过其键遍历哈希,然后打印每个值时,我得到"在连接(.)或字符串...中使用未初始化的值"警告.即使哈希显然已经预先初始化了.打印我想要的输出,但我仍然想知道为什么会导致警告,特别是直接访问值(在循环外部)没有警告的情况下工作.

#!/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";
}
Run Code Online (Sandbox Code Playgroud)

考虑上面的代码.我想perl看到了第一次打印和第二次打印之间的差异.但为什么?为什么检索循环外部的散列值和检索循环内部的has值之间有区别?

谢谢!

Mor*_*kus 17

在列表上下文中使用散列会产生键和值.因此,该行foreach my $key (%fruit)迭代键,值,键,值...

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