Why does this reduce {}, does not return the maximum value as expected?

I need to find the maximum value of all values ​​in a Perl hash. I do not need a key, just the highest value, so I can increase it and return a new value that is higher than before. The simplest thing in the world. I got inspiration from this answer: https://stackoverflow.com/a/3129441/ and implemented this piece of code:

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"; 

As you can see, the hash contains only two values ​​of 1. Then why does it print “2”? At least this happens on my machine.

I think I could just write

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

to get the maximum value, but I really would like to understand what is happening here.

+4
2

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)

values , (2). 2 || 0 2, .

,

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

, .

|| 0 ?

, , , , undef.

, , ,

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

or ||, values()

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

( , , )

+2

All Articles