# How to calculate factorial in Perl - n!

I was working on some examples when I had to calculate factorial. (n! in math)

The solution without any modules:

use strict; use warnings; use 5.010; my $f = 1; my $i = 1; my $n = 4; $f *= ++$i while $i < $n; say $f;

The solution when using the reduce function of the standard List::Util module:

use List::Util qw(reduce); my $fact = reduce { $a * $b } 1 .. $n; say $fact;

reduce will take the first two values of the list on the right hand side, assign them to $a and $b respectively, execute the block.

Then it will take the result, assign it to $a and take the next element from the list, assign it to $b and execute the block. This step will be repeated till the end of the list.

Published on 2015-04-02