Learn/Perl/6. Subroutines
Lesson 6 of 8
Sign in

Perl, lesson 6

Subroutines

Perl calls its functions subroutines. You define one with sub, give it a name, and put the body in braces:

Arguments arrive in @_

Perl doesn't name parameters in the sub line. Instead, every argument lands in a special array called @_. The first statement of a subroutine usually copies them into named variables:

my ($price, $rate) = @_; copies the first argument into $price and the second into $rate. Another common style takes them one at a time with shift, which removes and returns the first element of @_:

Always copy arguments into my variables. Working with directly can change the caller's variables by accident.

2 exercises to try what you just read.

Exercise 1

Shipping costs

Press Ctrl Enter or Check to test your code.

Exercise 2

Party bags

Press Ctrl Enter or Check to test your code.

@_

Signatures

Modern Perl can name parameters right in the sub line. Signatures are switched on by use v5.36; (or later):

With signatures, calling a sub with the wrong number of arguments is an error, which catches mistakes early. You can also give defaults: sub greet($name, $greeting = "Hello") { ... }. Both styles are common in real code, so it's worth knowing both.

Returning values

return sends a value back and leaves the subroutine. A sub can return a list, too:

Without return, a sub returns the value of its last statement, but an explicit return is clearer.

Scope

Variables declared with my inside a sub exist only inside that sub. Two subs can each have their own $total without interfering. A my variable declared at the top level of the file is visible to the code below it, including subs, but it's better to pass values in as arguments so each sub is self-contained.

Recursion

A sub can call itself:

Subs can be defined anywhere in the file, even after the code that calls them, because Perl compiles the whole file before it runs anything.

Further reading

  • perlintro: Writing subroutines
  • perlsub: Perl subroutines
  • perlsub: Signatures

Write sub shipping_cost using these rules:

  • up to 1 kg: 5
  • up to 5 kg: 12
  • up to 20 kg: 25
  • over 20 kg: 25 plus 2 for every kg above 20

The first input line is the number of parcels. Each following line holds one whole-number weight. For each parcel print <weight> kg costs <cost>, then print Total: <sum>.

Sample input:

Sample output:

You have some candies and some stickers and want to fill as many identical party bags as possible, using everything. The number of bags is the greatest common divisor (GCD) of the two amounts.

Write a recursive sub gcd using Euclid's rule: the GCD of x and 0 is x; otherwise the GCD of x and y equals the GCD of y and x % y. This starter uses use v5.36;, so you can write it with a signature.

Read the candies and the stickers (two whole numbers, at least 1, on one line separated by a space) and print:

Sample input:

Sample output:

use strict;
use warnings;

sub square {
    my ($n) = @_;
    return $n * $n;
}

print square(7), "\n";   # 49
sub price_with_tax {
    my ($price, $rate) = @_;
    return $price + $price * $rate;
}
sub greet {
    my $name = shift;
    my $greeting = shift // "Hello";     # // gives a default if the value is undef
    return "$greeting, $name!";
}

print greet("Ada"), "\n";              # Hello, Ada!
print greet("Ada", "Welcome"), "\n";   # Welcome, Ada!
use v5.36;

sub area($width, $height) {
    return $width * $height;
}

say area(3, 4);   # 12
sub min_max {
    my ($x, $y) = @_;
    return $x < $y ? ($x, $y) : ($y, $x);
}

my ($low, $high) = min_max(9, 4);   # 4 and 9
sub factorial {
    my ($n) = @_;
    return 1 if $n <= 1;
    return $n * factorial($n - 1);
}
3
1
4
23
1 kg costs 5
4 kg costs 12
23 kg costs 31
Total: 48
Bags: <n>
Each bag: <c> candies, <s> stickers
12 18
Bags: 6
Each bag: 2 candies, 3 stickers