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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With