Re: efficient max() function from sort
[email protected] (Rob Dixon)
| Newsgroups | perl.beginners |
|---|---|
| Message-ID | <[email protected]> |
Ramprasad A Padmanabhan wrote:
>
> I use sort to give the max of an array something like this
>
> -----
> my @z = qw(12 24 67 89 77 91 44 5 10);
> my $max = ((reverse sort{$a <=> $b} (@z))[0]);
> print "MAX = $max\n";
> -----------
>
> but when I am interested only in a single max value, I need not sort the
> entire array
Eugh. Where did you get this from? Hit them hard; with spoons.
OK, let's look at what you've written and try to make it visible.
my $max = ((reverse sort{$a <=> $b} (@z))[0]);
The parentheses around @z are superfluous are superfluous, so the inner call is
sort {$a <=> $b} @z
Now that's cool - we're sorting an array numerically. Next?
reverse sort {$a <=> $b} @z
Ouch. So we sort the contents of @z numerically into one list and then reverse
that list into a second. We could forget that reverse and just write
sort {$b <=> $a} @z
but we didn't do that. Never mind. Next?
Oh. We take just the the first element of the reversed sorted list with
(reverse sort {$a <=> $b} @z)[0]
So that's the maximum value. Fine. Now?
( (reverse sort {$a <=> $b} @z)[0] )
Someone thought we needed a list, so put some parentheses round that value.
And finally
my $max = ( (reverse sort {$a <=> $b} @z)[0] );
Oh. So that one-element list is being evaluated in scalar context after all.
Here are my thoughts.
- It's ugly
- It does mountains of unnecessary work
- It doesn't look like it works
- Few people can explain why it works
What you meant was either
$max = (sort {$a <=> $b} @z)[-1];
or
use List::Util qw/max/;
$max = max @z;
Big, hard spoons please.
Rob
> Is there a more efficient alternative to this
>
> PS: Posts via nntp to nntp.perl.org appear after a long time
> Is there a more preferred way of posting here