Perl Programming/Keywords/sub

From Wikibooks, open books for an open world
Jump to navigation Jump to search
Previous: study Keywords Next: substr

The sub keyword[edit | edit source]

The sub keyword defines a subroutine. Without a BLOCK, it is a forward declaration. By an assignment larger or shorter than LENGTH, the string will grow or shrink respectively to accommodate it. Without NAME, it defines an anonymous function, but returns the CODE ref of the just created closure.

Syntax[edit | edit source]

  sub NAME BLOCK
  sub NAME (PROTO) BLOCK
  sub NAME : ATTRIBUTES BLOCK
  sub NAME (PROTO) : ATTRIBUTES BLOCK

Examples[edit | edit source]

sub { $x = 1; };
sub sam { ... };
Previous: study Keywords Next: substr