> You can fing max and min value as,
>
> my @ar = (1,2,3,4,58,9,2,1);
> my $max = (sort { $b <=> $a } @ar)[0];
> my $min = (sort { $a <=> $b } @ar)[0];
If your arrays could be very large, it's a waste of cycles to sort the list
then throw most of that effort away. You could do:
**************************************
my @ar = (1,2,3,4,58,9,2,1);
my ($max, $min) = (-1e308, 1e308);
foreach (@ar) {
$max = $_ if $_ > $max;
$min = $_ if $_ < $min;
}
**************************************
Which only has to check each item once, instead of many times like the sort
algorithms do. Some smart perl person may know a better way (I know about
List::Util, but I avoid modules since we have some machines here with very
old versions of perl).
Also, I imagine the above code could be re-written as:
**************************************
my @ar = (1,2,3,4,58,9,2,1);
my ($min,$max) = (sort { $a <=> $b } @ar)[0,-1];
**************************************
.. to only do the sort once.
- Bryan
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/