9.4. Return a list

Perl allows us to return any number of values.

Example 9-5. examples/subroutines/fibonacci.pl

#!/usr/bin/perl
use strict;
use warnings;

my @numbers = fib(10);
print "@numbers\n";

sub fib {
    my $num = shift;

    my @fib;
    if ($num == 1) {
        return (1);
    } 
    if ($num == 2) {
        return (1, 1);
    }
    @fib = (1, 1);
    foreach (3..$num) {
        push @fib, $fib[-1]+$fib[-2];
    }
    return @fib;
}

If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed