Skip to Main Content
Perl in a Nutshell
book

Perl in a Nutshell

by Nathan Patwardhan, Ellen Siever, Stephen Spainhour
December 1998
Beginner to intermediate content levelBeginner to intermediate
674 pages
40h 41m
English
O'Reilly Media, Inc.
Content preview from Perl in a Nutshell

Subroutines

Subroutines are declared using one of these forms:

sub name {block}
sub name (proto) {block}

Prototypes allow you to put constraints on the arguments you provide to your subroutines.

You can also create anonymous subroutines at run-time, which will be available for use through a reference:

$subref = sub {block};

Calling Subroutines

The ampersand (&) is the identifier used to call subroutines. Most of the time, however, subroutines can be used in an expression just like built-in functions. To call subroutines directly:

                     name(args);                  # & is optional with parentheses
name 
                     args;                   # Parens optional if predeclared/imported
&name;                       # Passes current @_ to subroutine

To call subroutines indirectly (by name or by reference):

&$subref(args);                 # & is not optional on indirect call
&$subref;                       # Passes current @_ to subroutine

Passing Arguments

All arguments to a subroutine are passed as a single, flat list of scalars, and return values are returned the same way. Any arrays or hashes passed in these lists will have their values interpolated into the flattened list.

Any arguments passed to a subroutine come in as the array @_.

You may use the explicit return statement to return a value and leave the subroutine at any point.

Passing References

If you want to pass more than one array or hash into or out of a function and have them maintain their integrity, then you will want to pass references as arguments. The simplest way to do this is to take your named variables and put a backslash ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl One-Liners

Perl One-Liners

Peteris Krumins
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Mastering Perl

Mastering Perl

brian d foy
Perl Best Practices

Perl Best Practices

Damian Conway

Publisher Resources

ISBN: 1565922867Catalog PageErrata