Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does @_ -1 mean in Perl?

Tags:

arrays

php

perl

I'm trying to translate a Perl script to PHP and I'm having trouble with some Perl things. For instance, what does @_ -1 mean? And how do I write it in PHP?

The whole function is as follows:

sub variance {
    my $sum = sum_squares (@_);
    my $deg = @_ - 1;
    return $sum/$deg;
}

Ok, all the subroutines are as follows:

sub mean { # mean of values in an array
  my $sum = 0 ;
  foreach my $x (@_) {
    $sum += $x ;
  }
  return $sum/@_ ;
}

sub sum_squares { # sum of square differences from the mean
  my $mean = mean (@_) ;
  my $sum_squares = 0 ;
  foreach my $x (@_) {
    $sum_squares += ($x - $mean) ** 2 ;
  }
  return $sum_squares ;
}

sub variance { # variance of values in an array
  my $sum_squares = sum_squares (@_) ;
  my $deg_freedom = @_ - 1 ;
  return $sum_squares/$deg_freedom ;
}

sub median { # median of values in an array
  my @sorted = sort {$a <=> $b} (@_) ;
  if (1 == @sorted % 2) # Odd number of elements
    {return $sorted[($#sorted)/2]}
  else                   # Even number of elements
    {return ($sorted[($#sorted-1)/2]+$sorted[($#sorted+1)/2]) / 2}
}

sub histogram { # Counts of elements in an array
  my %histogram = () ;
  foreach my $value (@_) {$histogram{$value}++}
  return (%histogram) ;
}

Please bear with me because its my first time with Perl. From what I've seen (tested), the right answer in this case is the one of David Dorward. I do have another question regarding this set of subroutines that is here.

like image 856
Alex Avatar asked Feb 28 '10 22:02

Alex


1 Answers

In this case,@_ is the arguments passed to the subroutine, as a list.

Taken in scalar context, it is the number of elements in that list.

So if you call: variance('a', 'b', 'c', 'd');, $deg will be 3.

like image 147
Quentin Avatar answered Sep 21 '22 18:09

Quentin