Factorial in Perl
Example for versions
perl 5.8.8
This example uses the reduce
function from the List::Util
module. Note that we have to put an extra 1
in the beginning, so that it will work when 1 .. $n
is empty (i.e. when $n is 0).
use List::Util qw(reduce);
sub fact {
my $n = shift;
reduce { $a * $b } 1, 1 .. $n
}
foreach my $i (0..16) {
print "$i! = ", fact($i), "\n";
}
Comments
]]>blog comments powered by Disqus
]]>