Chapter 9. Functions and Subroutines

9.1. Subroutines

Example 9-1. examples/subroutines/subroutines.pl

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

my $sum = add(2, 3);
print "$sum\n";
print add(5, 8), "\n";

my $result = add2(4, 7);
print "$result\n";

print sum(3, 7, 11, 21), "\n";

sub add {
    my ($x, $y) = @_;

    my $z = $x+$y;
    return $z;
}

sub add2 {
    my $x = shift;
    my $y = shift;

    return $x+$y;
}

sub add_ugly {
    return $_[0]+$_[1];
}


sub sum {
    my $sum = 0;
    foreach my $v (@_) {
        $sum += $v;
    }
    return $sum;
}

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