gpt4 book ai didi

Perl - 为什么按其键循环散列然后打印每个值会导致未初始化的警告?

转载 作者:行者123 更新时间:2023-12-04 09:31:59 25 4
gpt4 key购买 nike

每当我通过它的键循环哈希,然后打印每个值时,我都会收到“在连接 (.) 或字符串中使用未初始化的值...”警告。即使散列已明确初始化。我想要的输出被打印出来,但我仍然想知道为什么这会导致警告,尤其是直接访问一个值(在循环外)没有警告的情况下。

#!/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";
}

考虑上面的代码。我猜 perl 看到了第一次打印和第二次打印之间的差异。但为什么?为什么在循环外检索哈希值与在循环内检索 has 值之间存在差异?

谢谢!

最佳答案

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

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

关于Perl - 为什么按其键循环散列然后打印每个值会导致未初始化的警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14275084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com