And if you want to go even more FP...
sub Gen_Stats {
my $stat = {};
my ($cnt, $max, $min, $tot);
$stat->{ADD} = sub {
$cnt += @_;
for ( @_ ) {
$tot += $_;
$max = $_ if ! defined $max || $_ > $max;
$min = $_ if ! defined $min || $_ < $min;
}
};
$stat->{MAX} = sub { $max };
$stat->{MIN} = sub { $min };
$stat->{AVE} = sub { $cnt ? $tot / $cnt : undef };
$stat->{TOT} = sub { $tot };
$stat->{ADD}->( @_ );
return $stat;
}
my $stat_info = Gen_Stats();
while ( <DATA> ) {
chomp;
$stat_info->{ADD}($_);
}
print join "\t", map { $_->() } @{$stat_info}{qw/MAX MIN AVE TOT/};
This code was borrowed from
RFC: Tool::Box. I recommend using
List::Util when and wherever possible. It has been part of the core since 5.007003 and uses XS when possible. The only real limitation I see with it is that all the items in the list must be known at once as I pointed out in
How A Function Becomes Higher Order.