sub
Named declarations:
subNAMEPROTOATTRSsubNAMEATTRSsubNAMEPROTOsubNAME
Named definitions:
subNAMEPROTOATTRSBLOCKsubNAMEATTRSBLOCKsubNAMEPROTOBLOCKsubNAMEBLOCK
Unnamed definitions:
subPROTOATTRSBLOCKsubATTRSBLOCKsubPROTOBLOCKsubBLOCK
The syntax of subroutine declarations and definitions looks complicated, but it is actually pretty simple in practice. Everything is based on the syntax:
subNAMEPROTOATTRSBLOCK
All four fields are optional; the only restrictions are that the
fields that do occur must occur in that order, and that you must use at
least one of NAME or
BLOCK. For the moment, we’ll ignore the
PROTO and ATTRS;
they’re just modifiers on the basic syntax. The
NAME and the BLOCK
are the important parts to get straight:
If you have just a
NAMEand noBLOCK, it’s a predeclaration of that name (but if you ever want to call the subroutine, you’ll have to supply a definition with both aNAMEand aBLOCKlater). Named declarations are useful because the parser treats a name specially if it knows it’s a user-defined subroutine. You can call such a subroutine either as a function or as an operator, just like built-in functions. These are sometimes called forward declarations.If you have both a
NAMEand aBLOCK, it’s a standard named subroutine definition (and a declaration, too, if you didn’t declare the name previously). Named definitions are useful because theBLOCKassociates an actual meaning (the body of the subroutine) with the declaration. That’s ...
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.
Read now
Unlock full access