Recursion in Perl
Last Updated :
02 Mar, 2023
Recursion is a mechanism when a function calls itself again and again till the required condition is met. When the function call statement is written inside the same function then such a function is referred to as a recursive function.
The argument passed to a function is retrieved from the default array @_ whereas each value can be accessed by $_[0], $_[1] and so on.
Example 1: The example below finds factorial of a number.
Factorial of any number n is (n)*(n-1)*(n-2)*....*1.
e.g.:
4! = 4*3*2*1 = 24
3! = 3*2*1 = 6
2! = 2*1 = 2
1! = 1
0! = 0
Perl
#!/usr/bin/perl
sub fact
{
my $x = $_ [0];
if ( $x == 0 || $x == 1)
{
return 1;
}
else
{
return $x * fact( $x - 1);
}
}
$a = 5;
print "Factorial of a number $a is " , fact( $a );
|
Here is how the program works :
Step 1- When the value of scalar a is 0 or 1, the function will return 1 because the value of both 0! and 1! is 1.
Step 2- When the value of scalar a is 2 then fac(x-1) makes a call to fac(1) and this function returns 1.
So, it is 2*factorial(1) = 2*1 = 2.So, it will return 2.
Step 3- Similarly when higher values are passed to function at every call argument value decreases by 1 and computes till the value reaches 1.
Example 2: Example below computes the Fibonacci series till a given number.
Perl
#!/usr/bin/perl
sub fib
{
my $x = shift ;
my $y = shift ;
my $n = shift ;
if ( $y > $n )
{
return 1;
}
print " $y" ;
fib( $y , $x + $y , $n );
}
$a = 5;
$c = 0;
$d = 1;
print "$c" ;
fib( $c , $d , $a );
|
Here is how the program works :
Step 1- Function fib() is called with 3 parameters starting values which will be 0 and 1 while $n is a number till which a series is to be printed
Step 2- These values are transferred in the form of an array whose values are retrieved with the use of shift.
Step 3- At each call first two values are retrieved using shift and these values are stored in scalars x and y. Now these two values are added to get the next value in the series. This step continues till the value reaches the ending value provided by the user.
Another approach using Recursion to print Fibonacci Series in Perl –
Perl
sub fibonacci {
my ( $num ) = @_ ;
if ( $num < 2) {
return $num ;
}
return fibonacci( $num -1) + fibonacci( $num -2);
}
print ( "Enter the number till the series will be printed : " );
$num = <>;
for ( $i = 0; $i < $num ; $i ++){
print (fibonacci( $i ), " " );
}
|
Output –
Share your thoughts in the comments
Please Login to comment...