Perl Language Creating subroutines


Example

Subroutines are created by using the keyword sub followed by an identifier and a code block enclosed in braces.

You can access the arguments by using the special variable @_, which contains all arguments as an array.

sub function_name {
    my ($arg1, $arg2, @more_args) = @_;
    # ...
}

Since the function shift defaults to shifting @_ when used inside a subroutine, it's a common pattern to extract the arguments sequentially into local variables at the beginning of a subroutine:

sub function_name {
    my $arg1 = shift;
    my $arg2 = shift;
    my @more_args = @_;
    # ...
}

# emulate named parameters (instead of positional)
sub function_name {
    my %args = (arg1 => 'default', @_);
    my $arg1 = delete $args{arg1};
    my $arg2 = delete $args{arg2};
    # ...
}

sub {
    my $arg1 = shift;
    # ...
}->($arg);
5.20.0

Alternatively, the experimental feature "signatures" can be used to unpack parameters, which are passed by value (not by reference).

use feature "signatures";

sub function_name($arg1, $arg2, @more_args) {
    # ...
}

Default values can be used for the parameters.

use feature "signatures";

sub function_name($arg1=1, $arg2=2) {
    # ...
}

You can use any expression to give a default value to a parameter – including other parameters.

sub function_name($arg1=1, $arg2=$arg1+1) {
    # ...
}

Note that you can't reference parameters which are defined after the current parameter – hence the following code doesn't work quite as expected.

sub function_name($arg1=$arg2, $arg2=1) {
    print $arg1;  # => <nothing>
    print $arg2;  # => 1
}