Ad space (banner)
Lesson 6 / 20

Writing a subroutine (a function)

This lesson covers the basic form for defining a function — a subroutine — in Perl.

A Perl function is defined as sub name { ... }. Arguments arrive through the special array variable @_.

The sample code defines sub greet { my $name = shift; return "Hello, ${name}!"; }, pulling the first argument out with shift.

A common early stumble is the relationship between @_ and shift. Rather than naming parameters in the definition as other languages do, Perl puts every argument into @_, from which you take them with shift or my ($a, $b) = @_;.

In professional work, gathering logic into a subroutine in one place, rather than copying it around, is what makes changes and maintenance manageable.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Perl directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)