O'Reilly logo

Perl Pocket Reference, 5th Edition by Johan Vromans

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Subroutines

Subroutines need a declaration, i.e., a specification of how they should be called, and a definition, i.e., a specification of what they should do when called.

sub name [ ( proto ) ] [ attributes ] ;

Declares name as a subroutine, optionally specifying the prototype and attributes. Declaring a subroutine is optional, but allows the subroutine to be called just like Perl’s built-in operators.

sub [ name ] [ ( proto ) ] [ attributes ] block

Defines subroutine name, with optional prototype and attributes. If the subroutine has been declared with a prototype or attributes, the definition should have the same prototype and attributes. When name is omitted, the subroutine is anonymous and the definition returns a reference to the code.

When a subroutine is called, the statements in block are executed. Parameters are passed as a flat list of scalars as array @_. The elements of @_ are aliases for the scalar parameters. The call returns the value of the last expression evaluated. wantarray (page 11) can be used to determine the context in which the subroutine was called.

Subroutines that have an empty prototype and do nothing but return a fixed value are inlined, e.g., sub PI() { 3.1415 }. See also the subsection Prototypes.

attributes are introduced with a : (colon). Perl supports the following attributes:

lvalue

The subroutine returns a scalar variable that can be assigned to.

method

The subroutine is a method.

There are several ways to call a subroutine.

name ( [ parameters ] )

The most ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required