P
PerseP
Hi,
I'm learning Perl by reading the "llama book". It happens that on the
answer to exercise 3 from chapter 4 (page 234), the authors ask why
the control variable in the subroutine &above_average is named
$element instead of using Perl's default $_.
The code is:
#!/usr/bin/perl
use strict;
sub total {
my $sum;
foreach(@_) {
$sum+=$_;
}
$sum;
}
sub average {
if (@_ ==0) { return; }
my $count =@_;
my $sum=&total(@_);
$sum/$count;
}
sub above_average {
my $average=&average(@_);
my @list;
my $element;
foreach $element (@_) {
if($element > $average) {
push @list,$element;
}
}
@list;
}
my @fred=&above_average(1..10);
print "\@fred is @fred\n";
print "(Should be 6 7 8 9 10)\n";
my @barney=&above_average(100,1..10);
print "\@barney is @barney\n";
print "(should be just 100)\n";
I've run the code as it's given above and with my initial answer,using
$_ instead of $elements:
sub above_average {
my $average=&average(@_);
my @list;
my $element;
foreach (@_) {
if($_ > $average) {
push @list,$_;
}
}
@list;
}
Both give the same output. So is there any point in using $element
instead of $_ as the control variable?
Thanks
I'm learning Perl by reading the "llama book". It happens that on the
answer to exercise 3 from chapter 4 (page 234), the authors ask why
the control variable in the subroutine &above_average is named
$element instead of using Perl's default $_.
The code is:
#!/usr/bin/perl
use strict;
sub total {
my $sum;
foreach(@_) {
$sum+=$_;
}
$sum;
}
sub average {
if (@_ ==0) { return; }
my $count =@_;
my $sum=&total(@_);
$sum/$count;
}
sub above_average {
my $average=&average(@_);
my @list;
my $element;
foreach $element (@_) {
if($element > $average) {
push @list,$element;
}
}
@list;
}
my @fred=&above_average(1..10);
print "\@fred is @fred\n";
print "(Should be 6 7 8 9 10)\n";
my @barney=&above_average(100,1..10);
print "\@barney is @barney\n";
print "(should be just 100)\n";
I've run the code as it's given above and with my initial answer,using
$_ instead of $elements:
sub above_average {
my $average=&average(@_);
my @list;
my $element;
foreach (@_) {
if($_ > $average) {
push @list,$_;
}
}
@list;
}
Both give the same output. So is there any point in using $element
instead of $_ as the control variable?
Thanks