Lesson 11 of 15

Subroutines

Subroutines

Functions in Perl are called subroutines. Define them with sub:

sub greet {
    my ($name) = @_;
    say "Hello, $name!";
}

greet("Alice");   # Hello, Alice!

The special array @_ contains the arguments passed to the subroutine.

Returning Values

The last expression evaluated is the return value, or use return explicitly:

sub add {
    my ($a, $b) = @_;
    return $a + $b;
}

say add(3, 4);   # 7

Multiple Parameters

sub max {
    my ($a, $b) = @_;
    if ($a > $b) {
        return $a;
    }
    return $b;
}

Your Task

Write a subroutine square that takes a number and returns its square. Print the square of 7.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.