perl - Why is this reduce {} not returning the max value as expected? -
I have to get the maximum value of all the values in the Pearl hash. I do not need a key, just the highest price, so that I can increase it and return a new value more than ever before. The simplest thing in the world is that I took inspiration from this reply: and implemented this piece of code:
Usage list :: UTL qw (minimum max); My% gid = ("abc" => 1, "def" => 1); My $ gid_ref = \% gid; My $ max_gid = reduce {$ a & gt; $ B? $ A: $ b} value% $ gid_ref || 0; Print "$ max_gid \ n"; As you can see, the hash is only in the form of values of two 1's. Then why is printing "2"? At least it does on my machine.
I think I can just write
my $ max2 = max (value% $ gid_ref) || 0; Anyway to get the maximum value, but I really want to understand what is happening here.
this line
max_gid = $ my decrease {$ a & Gt; $ B? $ A: $ b} value% $ gid_ref || 0; is parsed
$ max_gid = my $ {1 a & gt; $ B? $ A: $ b} (value% $ gid_ref = 0); Using values and
(value% $ gid_ref || 0) In the scalar context, which evaluates the number of elements in the hash (2). Since 2 || 0 is still 2 , you decrease it on a scalar and get back the value.
On the other hand
my $ max_gid = ({$ a> $ b? $ A: $ b} lower value% $ gid_ref) || 0; Receives maximum purpose.
What is the purpose of? 0 anyway? Recommended documentation
If your algorithm requires reducing the need to reduce the identified value, so make sure you always have the identity value, which back The first argument is to stop returning.
So you probably want
max_gid = my $ {1 a & gt; $ B? $ A: $ b} 0, value% $ gid_ref;
Comments
Post a Comment