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 with the same names as 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.

When the subroutine is invoked, the subroutine's code is run and any return value ...

Get Sams Teach Yourself Perl in 24 Hours 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.