Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does (sort {$a<=>$b;} @_)[0]; work?

Tags:

perl

I once read the following Perl subroutine

sub min{
  (sort  {$a<=>$b;}  @_)[0];
}

How to understand the usage of sort and @_ here? What does [0] stand for?

like image 556
user297850 Avatar asked Jun 21 '26 18:06

user297850


2 Answers

(...)[0] returns the first element of the list inside of the parentheses.

So your example is effectively the same as:

sub min{
  my @tmp = sort { $a <=> $b } @_; # sort numerically
  $tmp[0];
}

or

sub min{
  my ($return) = sort { $a <=> $b } @_; # sort numerically
  $return;
}

I would like to point out one more thing, the code above is wildly inefficient. Especially on large unsorted lists.

Here is a more sensible approach:

sub min{
  $min = shift;
  for( @_ ){
    $min = $_ if $_ < $min;
  }
  return $min;
}

This is basically the same algorithm used for the Pure Perl version of min in List::Util.

You really should just be using min from List::Util.

like image 116
Brad Gilbert Avatar answered Jun 25 '26 05:06

Brad Gilbert


This numerically sorts the parameters to the sub (which are in the array @_) and returns the first element of the result (which is in [0]). The first element is the minimum of all of the args. It assumes they are all numeric.

like image 39
Bill Ruppert Avatar answered Jun 25 '26 05:06

Bill Ruppert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!