user297850
user297850

Reputation: 8015

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

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?

Upvotes: 2

Views: 514

Answers (2)

Brad Gilbert
Brad Gilbert

Reputation: 34120

(...)[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.

Upvotes: 10

Bill Ruppert
Bill Ruppert

Reputation: 9016

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.

Upvotes: 3

Related Questions