Fibonacci numbers are a favorite way to demonstrate recursion (along with the factorial that I use in Mastering Perl ). Your example is fine, but you should also know that you do not need this feature in many cases.
Here's an iterative solution that creates a sequence from the lower end, not the high end. You do not need to return, because you already know the answers to the calculations necessary for the next step:
use v5.20; use experimental qw(signatures); no warnings qw(experimental::signatures); sub fibonacci ( $n ) { my @numbers = qw( 0 1 ); foreach ( 2 .. $n ) { $numbers[ $_ ] = $numbers[ $_ - 1 ] + $numbers[ $_ - 2 ]; } return @numbers[ 0 .. $n ]; } my @series = fibonacci( 1 ); say "Fibo Series : @series";
This gets even better, because you can change this to use state to remember previous calculations. You should use an array reference, since state cannot initialize the array, but this is not very important:
use v5.22; use experimental qw(signatures postderef); no warnings qw(experimental::signatures experimental::postderef); sub fibonacci ( $n ) { state $numbers = [ qw( 0 1 ) ]; foreach ( $#$numbers .. $n ) { $numbers->[ $_ ] = $numbers->[ $_ - 1 ] + $numbers->[ $_ - 2 ]; } return $numbers->@[ 0 .. $n ]; } my @series = fibonacci( 17 ); say "Fibo Series : @series";
source share