Creating and Calling Subroutines

You create user-defined subroutines in Perl by using the following syntax:

sub subroutine_name {
    statement1;
    :
    statementx;
}

Subroutine names in Perl follow the same naming conventions as scalars, arrays, and hashes outlined in Hour 2, “Perl's Building Blocks: Numbers and Strings.” Subroutine names can have the same names as existing variables. However, you should avoid creating subroutine names that are the same as those of Perl's built-in functions and operators. Creating two subroutines with the same name in Perl causes Perl to emit a warning if warnings are enabled; otherwise, the second definition causes the first to be forgotten.

Here is an example of a subroutine:

 sub countdown { for ($i=10; $i>=0; $i--) ...

Get SAMS Teach Yourself Perl in 24 Hours THIRD EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.