perl – 为什么减少{}没有按预期返回最大值?

前端之家收集整理的这篇文章主要介绍了perl – 为什么减少{}没有按预期返回最大值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在Perl哈希中找到所有值的最大值.我不需要键,只需要最高值,这样我就可以增加它并返回一个比以前更高的新值.世界上最简单的事情.我从这个答案中获取灵感: https://stackoverflow.com/a/2891180/2740187,并实现了这段代码

use List::Util qw( reduce min max );
my %gid = ("abc" => 1,"def" => 1);
my $gid_ref = \%gid;
my $max_gid = reduce { $a > $b ? $a : $b } values %$gid_ref || 0;
print "$max_gid\n";

如您所见,哈希只包含两个1作为值.那为什么打印“2”?至少它在我的机器上.

我想我只能写

my $max2 = max(values %$gid_ref) || 0;

无论如何要获得最大值,但我真的想了解这里发生了什么.

解决方法

这条线

my $max_gid = reduce { $a > $b ? $a : $b } values %$gid_ref || 0;

被解析为

my $max_gid = reduce { $a > $b ? $a : $b } (values %$gid_ref || 0);

(values %$gid_ref || 0)

在标量上下文中使用值,该值计算哈希值(2)中的元素数量.自2 || 0仍然是2,你在标量上执行缩减并返回值.

另一方面

my $max_gid = (reduce { $a > $b ? $a : $b } values %$gid_ref) || 0;

确实按预期获得序列的最大值.

什么是||的目的0无论如何?文档建议

If your algorithm requires that reduce produce an identity value,then make sure that you always pass that identity value as the first argument to prevent undef being returned.

所以你可能想要

my $max_gid = reduce { $a > $b ? $a : $b } 0,values %$gid_ref;

猜你在找的Perl相关文章