Functions in Perl
Functions are central in Perl. We’ll learn about functions with a few different examples.
To run the script, save it as functions.pl
and use the perl
command:
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.