VOOZH about

URL: https://www.geeksforgeeks.org/perl/recursion-in-perl/

⇱ Recursion in Perl - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Recursion in Perl

Last Updated : 2 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


 

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. 
 

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 - 

Output - 

👁 Image
 


 

Comment
Article Tags:

Explore