Perl version

  • Preferences

Manual

  • Overview
  • Tutorials
  • FAQs
  • History / Changes
  • License

Reference

  • Language
  • Functions
  • Operators
  • Special Variables
  • Pragmas
  • Utilities
  • Internals
  • Platform Specific

Modules

  • A • B • C • D • E
  • F • G • H • I • L
  • M • N • O • P • S
  • T • U • X

perlsub

Perl 5 version 20.1 documentation
Recently read

perlsub

  • NAME
  • SYNOPSIS
  • DESCRIPTION
    • Signatures
    • Private Variables via my()
    • Persistent Private Variables
    • Temporary Values via local()
    • Lvalue subroutines
    • Lexical Subroutines
    • Passing Symbol Table Entries (typeglobs)
    • When to Still Use local()
    • Pass by Reference
    • Prototypes
    • Constant Functions
    • Overriding Built-in Functions
    • Autoloading
    • Subroutine Attributes
  • SEE ALSO

NAME

perlsub - Perl subroutines

SYNOPSIS

To declare subroutines:

  1. sub NAME; # A "forward" declaration.
  2. sub NAME(PROTO); # ditto, but with prototypes
  3. sub NAME : ATTRS; # with attributes
  4. sub NAME(PROTO) : ATTRS; # with attributes and prototypes
  5. sub NAME BLOCK # A declaration and a definition.
  6. sub NAME(PROTO) BLOCK # ditto, but with prototypes
  7. sub NAME SIG BLOCK # with signature
  8. sub NAME : ATTRS BLOCK # with attributes
  9. sub NAME(PROTO) : ATTRS BLOCK # with prototypes and attributes
  10. sub NAME : ATTRS SIG BLOCK # with attributes and signature

To define an anonymous subroutine at runtime:

  1. $subref = sub BLOCK; # no proto
  2. $subref = sub (PROTO) BLOCK; # with proto
  3. $subref = sub SIG BLOCK; # with signature
  4. $subref = sub : ATTRS BLOCK; # with attributes
  5. $subref = sub (PROTO) : ATTRS BLOCK; # with proto and attributes
  6. $subref = sub : ATTRS SIG BLOCK; # with attribs and signature

To import subroutines:

  1. use MODULE qw(NAME1 NAME2 NAME3);

To call subroutines:

  1. NAME(LIST); # & is optional with parentheses.
  2. NAME LIST; # Parentheses optional if predeclared/imported.
  3. &NAME(LIST); # Circumvent prototypes.
  4. &NAME; # Makes current @_ visible to called subroutine.

DESCRIPTION

Like many languages, Perl provides for user-defined subroutines. These may be located anywhere in the main program, loaded in from other files via the do, require, or use keywords, or generated on the fly using eval or anonymous subroutines. You can even call a function indirectly using a variable containing its name or a CODE reference.

The Perl model for function call and return values is simple: all functions are passed as parameters one single flat list of scalars, and all functions likewise return to their caller one single flat list of scalars. Any arrays or hashes in these call and return lists will collapse, losing their identities--but you may always use pass-by-reference instead to avoid this. Both call and return lists may contain as many or as few scalar elements as you'd like. (Often a function without an explicit return statement is called a subroutine, but there's really no difference from Perl's perspective.)

Any arguments passed in show up in the array @_ . (They may also show up in lexical variables introduced by a signature; see Signatures below.) Therefore, if you called a function with two arguments, those would be stored in $_[0] and $_[1] . The array @_ is a local array, but its elements are aliases for the actual scalar parameters. In particular, if an element $_[0] is updated, the corresponding argument is updated (or an error occurs if it is not updatable). If an argument is an array or hash element which did not exist when the function was called, that element is created only when (and if) it is modified or a reference to it is taken. (Some earlier versions of Perl created the element whether or not the element was assigned to.) Assigning to the whole array @_ removes that aliasing, and does not update any arguments.

A return statement may be used to exit a subroutine, optionally specifying the returned value, which will be evaluated in the appropriate context (list, scalar, or void) depending on the context of the subroutine call. If you specify no return value, the subroutine returns an empty list in list context, the undefined value in scalar context, or nothing in void context. If you return one or more aggregates (arrays and hashes), these will be flattened together into one large indistinguishable list.

If no return is found and if the last statement is an expression, its value is returned. If the last statement is a loop control structure like a foreach or a while , the returned value is unspecified. The empty sub returns the empty list.

Aside from an experimental facility (see Signatures below), Perl does not have named formal parameters. In practice all you do is assign to a my() list of these. Variables that aren't declared to be private are global variables. For gory details on creating private variables, see Private Variables via my() and Temporary Values via local(). To create protected environments for a set of functions in a separate package (and probably a separate file), see Packages in perlmod.

Example:

  1. sub max {
  2. my $max = shift(@_);
  3. foreach $foo (@_) {
  4. $max = $foo if $max < $foo;
  5. }
  6. return $max;
  7. }
  8. $bestday = max($mon,$tue,$wed,$thu,$fri);

Example:

  1. # get a line, combining continuation lines
  2. # that start with whitespace
  3. sub get_line {
  4. $thisline = $lookahead; # global variables!
  5. LINE: while (defined($lookahead = <STDIN>)) {
  6. if ($lookahead =~ /^[ \t]/) {
  7. $thisline .= $lookahead;
  8. }
  9. else {
  10. last LINE;
  11. }
  12. }
  13. return $thisline;
  14. }
  15. $lookahead = <STDIN>; # get first line
  16. while (defined($line = get_line())) {
  17. ...
  18. }

Assigning to a list of private variables to name your arguments:

  1. sub maybeset {
  2. my($key, $value) = @_;
  3. $Foo{$key} = $value unless $Foo{$key};
  4. }

Because the assignment copies the values, this also has the effect of turning call-by-reference into call-by-value. Otherwise a function is free to do in-place modifications of @_ and change its caller's values.

  1. upcase_in($v1, $v2); # this changes $v1 and $v2
  2. sub upcase_in {
  3. for (@_) { tr/a-z/A-Z/ }
  4. }

You aren't allowed to modify constants in this way, of course. If an argument were actually literal and you tried to change it, you'd take a (presumably fatal) exception. For example, this won't work:

  1. upcase_in("frederick");

It would be much safer if the upcase_in() function were written to return a copy of its parameters instead of changing them in place:

  1. ($v3, $v4) = upcase($v1, $v2); # this doesn't change $v1 and $v2
  2. sub upcase {
  3. return unless defined wantarray; # void context, do nothing
  4. my @parms = @_;
  5. for (@parms) { tr/a-z/A-Z/ }
  6. return wantarray ? @parms : $parms[0];
  7. }

Notice how this (unprototyped) function doesn't care whether it was passed real scalars or arrays. Perl sees all arguments as one big, long, flat parameter list in @_ . This is one area where Perl's simple argument-passing style shines. The upcase() function would work perfectly well without changing the upcase() definition even if we fed it things like this:

  1. @newlist = upcase(@list1, @list2);
  2. @newlist = upcase( split /:/, $var );

Do not, however, be tempted to do this:

  1. (@a, @b) = upcase(@list1, @list2);

Like the flattened incoming parameter list, the return list is also flattened on return. So all you have managed to do here is stored everything in @a and made @b empty. See Pass by Reference for alternatives.

A subroutine may be called using an explicit & prefix. The & is optional in modern Perl, as are parentheses if the subroutine has been predeclared. The & is not optional when just naming the subroutine, such as when it's used as an argument to defined() or undef(). Nor is it optional when you want to do an indirect subroutine call with a subroutine name or reference using the &$subref() or &{$subref}() constructs, although the $subref->() notation solves that problem. See perlref for more about all that.

Subroutines may be called recursively. If a subroutine is called using the & form, the argument list is optional, and if omitted, no @_ array is set up for the subroutine: the @_ array at the time of the call is visible to subroutine instead. This is an efficiency mechanism that new users may wish to avoid.

  1. &foo(1,2,3); # pass three arguments
  2. foo(1,2,3); # the same
  3. foo(); # pass a null list
  4. &foo(); # the same
  5. &foo; # foo() get current args, like foo(@_) !!
  6. foo; # like foo() IFF sub foo predeclared, else "foo"

Not only does the & form make the argument list optional, it also disables any prototype checking on arguments you do provide. This is partly for historical reasons, and partly for having a convenient way to cheat if you know what you're doing. See Prototypes below.

Since Perl 5.16.0, the __SUB__ token is available under use feature 'current_sub' and use 5.16.0 . It will evaluate to a reference to the currently-running sub, which allows for recursive calls without knowing your subroutine's name.

  1. use 5.16.0;
  2. my $factorial = sub {
  3. my ($x) = @_;
  4. return 1 if $x == 1;
  5. return($x * __SUB__->( $x - 1 ) );
  6. };

The behaviour of __SUB__ within a regex code block (such as /(?{...})/ ) is subject to change.

Subroutines whose names are in all upper case are reserved to the Perl core, as are modules whose names are in all lower case. A subroutine in all capitals is a loosely-held convention meaning it will be called indirectly by the run-time system itself, usually due to a triggered event. Subroutines whose name start with a left parenthesis are also reserved the same way. The following is a list of some subroutines that currently do special, pre-defined things.

  • documented later in this document

    AUTOLOAD

  • documented in perlmod

    CLONE , CLONE_SKIP ,

  • documented in perlobj

    DESTROY

  • documented in perltie

    BINMODE , CLEAR , CLOSE , DELETE , DESTROY , EOF , EXISTS , EXTEND , FETCH , FETCHSIZE , FILENO , FIRSTKEY , GETC , NEXTKEY , OPEN , POP , PRINT , PRINTF , PUSH , READ , READLINE , SCALAR , SEEK , SHIFT , SPLICE , STORE , STORESIZE , TELL , TIEARRAY , TIEHANDLE , TIEHASH , TIESCALAR , UNSHIFT , UNTIE , WRITE

  • documented in PerlIO::via

    BINMODE , CLEARERR , CLOSE , EOF , ERROR , FDOPEN , FILENO , FILL , FLUSH , OPEN , POPPED , PUSHED , READ , SEEK , SETLINEBUF , SYSOPEN , TELL , UNREAD , UTF8 , WRITE

  • documented in perlfunc

    use, use, require

  • documented in UNIVERSAL

    VERSION

  • documented in perldebguts

    DB::DB , DB::sub , DB::lsub , DB::goto , DB::postponed

  • undocumented, used internally by the overload feature

    any starting with (

The BEGIN , UNITCHECK , CHECK , INIT and END subroutines are not so much subroutines as named special code blocks, of which you can have more than one in a package, and which you can not call explicitly. See BEGIN, UNITCHECK, CHECK, INIT and END in perlmod

Signatures

WARNING: Subroutine signatures are experimental. The feature may be modified or removed in future versions of Perl.

Perl has an experimental facility to allow a subroutine's formal parameters to be introduced by special syntax, separate from the procedural code of the subroutine body. The formal parameter list is known as a signature. The facility must be enabled first by a pragmatic declaration, use feature 'signatures' , and it will produce a warning unless the "experimental::signatures" warnings category is disabled.

The signature is part of a subroutine's body. Normally the body of a subroutine is simply a braced block of code. When using a signature, the signature is a parenthesised list that goes immediately before the braced block. The signature declares lexical variables that are in scope for the block. When the subroutine is called, the signature takes control first. It populates the signature variables from the list of arguments that were passed. If the argument list doesn't meet the requirements of the signature, then it will throw an exception. When the signature processing is complete, control passes to the block.

Positional parameters are handled by simply naming scalar variables in the signature. For example,

  1. sub foo ($left, $right) {
  2. return $left + $right;
  3. }

takes two positional parameters, which must be filled at runtime by two arguments. By default the parameters are mandatory, and it is not permitted to pass more arguments than expected. So the above is equivalent to

  1. sub foo {
  2. die "Too many arguments for subroutine" unless @_ <= 2;
  3. die "Too few arguments for subroutine" unless @_ >= 2;
  4. my $left = $_[0];
  5. my $right = $_[1];
  6. return $left + $right;
  7. }

An argument can be ignored by omitting the main part of the name from a parameter declaration, leaving just a bare $ sigil. For example,

  1. sub foo ($first, $, $third) {
  2. return "first=$first, third=$third";
  3. }

Although the ignored argument doesn't go into a variable, it is still mandatory for the caller to pass it.

A positional parameter is made optional by giving a default value, separated from the parameter name by = :

  1. sub foo ($left, $right = 0) {
  2. return $left + $right;
  3. }

The above subroutine may be called with either one or two arguments. The default value expression is evaluated when the subroutine is called, so it may provide different default values for different calls. It is only evaluated if the argument was actually omitted from the call. For example,

  1. my $auto_id = 0;
  2. sub foo ($thing, $id = $auto_id++) {
  3. print "$thing has ID $id";
  4. }

automatically assigns distinct sequential IDs to things for which no ID was supplied by the caller. A default value expression may also refer to parameters earlier in the signature, making the default for one parameter vary according to the earlier parameters. For example,

  1. sub foo ($first_name, $surname, $nickname = $first_name) {
  2. print "$first_name $surname is known as \"$nickname\"";
  3. }

An optional parameter can be nameless just like a mandatory parameter. For example,

  1. sub foo ($thing, $ = 1) {
  2. print $thing;
  3. }

The parameter's default value will still be evaluated if the corresponding argument isn't supplied, even though the value won't be stored anywhere. This is in case evaluating it has important side effects. However, it will be evaluated in void context, so if it doesn't have side effects and is not trivial it will generate a warning if the "void" warning category is enabled. If a nameless optional parameter's default value is not important, it may be omitted just as the parameter's name was:

  1. sub foo ($thing, $=) {
  2. print $thing;
  3. }

Optional positional parameters must come after all mandatory positional parameters. (If there are no mandatory positional parameters then an optional positional parameters can be the first thing in the signature.) If there are multiple optional positional parameters and not enough arguments are supplied to fill them all, they will be filled from left to right.

After positional parameters, additional arguments may be captured in a slurpy parameter. The simplest form of this is just an array variable:

  1. sub foo ($filter, @inputs) {
  2. print $filter->($_) foreach @inputs;
  3. }

With a slurpy parameter in the signature, there is no upper limit on how many arguments may be passed. A slurpy array parameter may be nameless just like a positional parameter, in which case its only effect is to turn off the argument limit that would otherwise apply:

  1. sub foo ($thing, @) {
  2. print $thing;
  3. }

A slurpy parameter may instead be a hash, in which case the arguments available to it are interpreted as alternating keys and values. There must be as many keys as values: if there is an odd argument then an exception will be thrown. Keys will be stringified, and if there are duplicates then the later instance takes precedence over the earlier, as with standard hash construction.

  1. sub foo ($filter, %inputs) {
  2. print $filter->($_, $inputs{$_}) foreach sort keys %inputs;
  3. }

A slurpy hash parameter may be nameless just like other kinds of parameter. It still insists that the number of arguments available to it be even, even though they're not being put into a variable.

  1. sub foo ($thing, %)
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.