Functions in Perl

Functions are central in Perl. We’ll learn about functions with a few different examples.

use strict;
use warnings;

# Here's a function that takes two numbers and returns
# their sum.
sub plus {
    my ($a, $b) = @_;
    return $a + $b;
}

# In Perl, you can omit parentheses when calling functions
# with arguments, but it's often clearer to include them.
sub plus_plus {
    my ($a, $b, $c) = @_;
    return $a + $b + $c;
}

# The main part of our script
my $res = plus(1, 2);
print "1+2 = $res\n";

$res = plus_plus(1, 2, 3);
print "1+2+3 = $res\n";

To run the script, save it as functions.pl and use the perl command:

$ perl functions.pl
1+2 = 3
1+2+3 = 6

In Perl, functions are defined using the sub keyword. They can take any number of arguments, which are passed in the special array @_. It’s common to assign these arguments to named variables at the start of the function for clarity.

Perl doesn’t require explicit return types, and will automatically return the value of the last expression in a function if no return statement is given. However, it’s often clearer to use explicit return statements.

When calling a function, you can use parentheses to group the arguments, which is especially useful for nested function calls or when passing the result of a function as an argument to another function.

Perl also supports multiple return values, which we’ll look at next.