The first line is the shebang, which specifies which version of Perl to use.
#!/usr/bin/perl
The next two lines will help you catch mistakes in your program and make sure you are coding properly. See Why use strict and warnings?
use warnings;
use strict;
print
will print the message in quotes.
print "Enter in a number\n";
The diamond operator, <>
, used in this context, is the same as calling readline. It will read the input from STDIN
.
my $input=<>;
The next line is calling the subroutine fact
with $input
as an argument.
my $num= fact($input);
Printing the result. $input
and $num
will be interpolated because you are using double quotes.
print "The factorial of $input is $num\n";
Finally, the part you are most interested in.
sub fact{
my $val = $_[0];
if ($val > 1) {
$num = $val * fact($val-1);
} else {
$num = 1;
}
}
The first line of this subroutine my $val = $_[0];
, is setting $val
equal to the value you call it with. The first time through, you call is with $input
, so $val
will be set to that value.
Next, we have this if else
statement. Suppose you enter 5
on the command line, so $input
was 5
. In that case, it is greater than 1
. It will execute the statement $num = $val * fact($val-1);
. Seeing as the value of $val
is 5
, it would be the same as calling $num = 5 * fact(4);
.
If we were going to continue looking at the what code is executing, you'll see that now we are calling fact(4);
. Since 4 > 1
it will pass the if statement again, and then call fact(3)
.
Each time we are multiplying the number by that number minus one, such as $val = 5 * 4 * 3 * 2 * 1
.
From perlsub
If no return is found and if the last statement is an expression, its
value is returned. If the last statement is a loop control structure
like a foreach or a while , the returned value is unspecified. The
empty sub returns the empty list.
So this is why we don't have to return $num
at the end of your fact
subroutine, but it may be useful to add to increase readability.
Just to break down what this is doing.
$num = 5 * fact(4);
fact(4)
is equivalent to 4 * fact(3)
.
$num = 5 * (4 * fact(3));
fact(3)
is equivalent to 3 * fact(2)
.
$num = 5 * (4 * (3 * fact(2)));
fact(2)
is equivalent to 2 * fact(1)
.
$num = 5 * (4 * (3 * (2 * fact(1)));
fact(1)
is equivalent to 1
.
$num = 5 * (4 * (3 * (2 * 1));
Search recursion
on Google for another example (did you mean recursion?).