in reply to How to get the index of smallest whole number in an array?

List::Util::reduce()

my @array = ('3','4','71','1', '-598', '-100203'); print reduce{ $a = $b if $array[$b] >=0 and $array[$b] < $array[$a]; $ +a } 0 .. $#array;; 3

Or more simply:

print reduce{ $array[$b] >=0 && $array[$b] < $array[$a] ? $b : $a } 0 +.. $#array;

Bad data -- ie. empty array, or all negatives -- returns undef. Doesn't check values are integer.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority". The enemy of (IT) success is complexity.
In the absence of evidence, opinion is indistinguishable from prejudice. Suck that fhit

Replies are listed 'Best First'.
Re^2: How to get the index of smallest whole number in an array? (Simplified)
by Eily (Monsignor) on Jul 06, 2018 at 08:28 UTC

    all negatives -- returns undef
    No you get 0 with all negatives, since the first thing reduce does is set $a to the first value in the list. Though there is more than one way to solve this, I didn't find a one that doesn't involve re-checking $a on each iteration.