my %number_words = hash_a_file($_);
foreach my $key ( keys %number_words ) {
++$word_list{$key};
}
这是有效的,但我想避免使用中间变量 像这样
foreach my $key ( keys hash_a_file($_) ) {
++$word_list{$key};
}
我尝试使用ref但仍然失败了。有什么办法吗?谢谢!
答案 0 :(得分:4)
问题是,子程序不返回哈希值。它返回一个列表。在原始代码中,只有在将其存储在哈希变量中时才会成为哈希值。
但是还有其他方法可以从列表中创建哈希。您可以创建匿名哈希,然后取消引用它。这很难看,但它确实有效。
# Inner braces create an anonymous hash.
# Outer braces de-reference that into a "real" hash
foreach my $key ( keys %{ { hash_a_file($_) } } ) {
++$word_list{$key};
}
更新:要备份Borodin的评论,我应该补充一点,如果在代码审查中将此代码呈现给我,我建议将其重写为使用显式哈希变量作为原始代码确实
答案 1 :(得分:1)
返回一个hashref,以便为keys
(而不是列表)形成一个有效的参数
sub hash_a_file { return { a => 1, b => 2 } }
foreach my $key ( keys %{ hash_a_file() } ) {
say $key
}