{
    "mode": "man",
    "parameter": "perlsub",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/perlsub/1/json",
    "generated": "2026-06-15T14:24:58Z",
    "synopsis": "To declare subroutines:\nsub NAME;                     # A \"forward\" declaration.\nsub NAME(PROTO);              #  ditto, but with prototypes\nsub NAME : ATTRS;             #  with attributes\nsub NAME(PROTO) : ATTRS;      #  with attributes and prototypes\nsub NAME BLOCK                # A declaration and a definition.\nsub NAME(PROTO) BLOCK         #  ditto, but with prototypes\nsub NAME : ATTRS BLOCK        #  with attributes\nsub NAME(PROTO) : ATTRS BLOCK #  with prototypes and attributes\nuse feature 'signatures';\nsub NAME(SIG) BLOCK                    # with signature\nsub NAME :ATTRS (SIG) BLOCK            # with signature, attributes\nsub NAME :prototype(PROTO) (SIG) BLOCK # with signature, prototype\nTo define an anonymous subroutine at runtime:\n$subref = sub BLOCK;                 # no proto\n$subref = sub (PROTO) BLOCK;         # with proto\n$subref = sub : ATTRS BLOCK;         # with attributes\n$subref = sub (PROTO) : ATTRS BLOCK; # with proto and attributes\nuse feature 'signatures';\n$subref = sub (SIG) BLOCK;           # with signature\n$subref = sub : ATTRS(SIG) BLOCK;    # with signature, attributes\nTo import subroutines:\nuse MODULE qw(NAME1 NAME2 NAME3);\nTo call subroutines:\nNAME(LIST);    # & is optional with parentheses.\nNAME LIST;     # Parentheses optional if predeclared/imported.\n&NAME(LIST);   # Circumvent prototypes.\n&NAME;         # Makes current @ visible to called subroutine.",
    "sections": {
        "NAME": {
            "content": "perlsub - Perl subroutines\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "To declare subroutines:\n\nsub NAME;                     # A \"forward\" declaration.\nsub NAME(PROTO);              #  ditto, but with prototypes\nsub NAME : ATTRS;             #  with attributes\nsub NAME(PROTO) : ATTRS;      #  with attributes and prototypes\n\nsub NAME BLOCK                # A declaration and a definition.\nsub NAME(PROTO) BLOCK         #  ditto, but with prototypes\nsub NAME : ATTRS BLOCK        #  with attributes\nsub NAME(PROTO) : ATTRS BLOCK #  with prototypes and attributes\n\nuse feature 'signatures';\nsub NAME(SIG) BLOCK                    # with signature\nsub NAME :ATTRS (SIG) BLOCK            # with signature, attributes\nsub NAME :prototype(PROTO) (SIG) BLOCK # with signature, prototype\n\nTo define an anonymous subroutine at runtime:\n\n$subref = sub BLOCK;                 # no proto\n$subref = sub (PROTO) BLOCK;         # with proto\n$subref = sub : ATTRS BLOCK;         # with attributes\n$subref = sub (PROTO) : ATTRS BLOCK; # with proto and attributes\n\nuse feature 'signatures';\n$subref = sub (SIG) BLOCK;           # with signature\n$subref = sub : ATTRS(SIG) BLOCK;    # with signature, attributes\n\nTo import subroutines:\n\nuse MODULE qw(NAME1 NAME2 NAME3);\n\nTo call subroutines:\n\nNAME(LIST);    # & is optional with parentheses.\nNAME LIST;     # Parentheses optional if predeclared/imported.\n&NAME(LIST);   # Circumvent prototypes.\n&NAME;         # Makes current @ visible to called subroutine.\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "Like many languages, Perl provides for user-defined subroutines.  These may be located\nanywhere in the main program, loaded in from other files via the \"do\", \"require\", or \"use\"\nkeywords, or generated on the fly using \"eval\" or anonymous subroutines.  You can even call a\nfunction indirectly using a variable containing its name or a CODE reference.\n\nThe Perl model for function call and return values is simple: all functions are passed as\nparameters one single flat list of scalars, and all functions likewise return to their caller\none single flat list of scalars.  Any arrays or hashes in these call and return lists will\ncollapse, losing their identities--but you may always use pass-by-reference instead to avoid\nthis.  Both call and return lists may contain as many or as few scalar elements as you'd\nlike.  (Often a function without an explicit return statement is called a subroutine, but\nthere's really no difference from Perl's perspective.)\n\nAny arguments passed in show up in the array @.  (They may also show up in lexical variables\nintroduced by a signature; see \"Signatures\" below.)  Therefore, if you called a function with\ntwo arguments, those would be stored in $[0] and $[1].  The array @ is a local array, but\nits elements are aliases for the actual scalar parameters.  In particular, if an element\n$[0] is updated, the corresponding argument is updated (or an error occurs if it is not\nupdatable).  If an argument is an array or hash element which did not exist when the function\nwas called, that element is created only when (and if) it is modified or a reference to it is\ntaken.  (Some earlier versions of Perl created the element whether or not the element was\nassigned to.)  Assigning to the whole array @ removes that aliasing, and does not update any\narguments.\n\nA \"return\" statement may be used to exit a subroutine, optionally specifying the returned\nvalue, which will be evaluated in the appropriate context (list, scalar, or void) depending\non the context of the subroutine call.  If you specify no return value, the subroutine\nreturns an empty list in list context, the undefined value in scalar context, or nothing in\nvoid context.  If you return one or more aggregates (arrays and hashes), these will be\nflattened together into one large indistinguishable list.\n\nIf no \"return\" is found and if the last statement is an expression, its value is returned.\nIf the last statement is a loop control structure like a \"foreach\" or a \"while\", the returned\nvalue is unspecified.  The empty sub returns the empty list.\n\nAside from an experimental facility (see \"Signatures\" below), Perl does not have named formal\nparameters.  In practice all you do is assign to a \"my()\" list of these.  Variables that\naren't declared to be private are global variables.  For gory details on creating private\nvariables, see \"Private Variables via my()\" and \"Temporary Values via local()\".  To create\nprotected environments for a set of functions in a separate package (and probably a separate\nfile), see \"Packages\" in perlmod.\n\nExample:\n\nsub max {\nmy $max = shift(@);\nforeach $foo (@) {\n$max = $foo if $max < $foo;\n}\nreturn $max;\n}\n$bestday = max($mon,$tue,$wed,$thu,$fri);\n\nExample:\n\n# get a line, combining continuation lines\n#  that start with whitespace\n\nsub getline {\n$thisline = $lookahead;  # global variables!\nLINE: while (defined($lookahead = <STDIN>)) {\nif ($lookahead =~ /^[ \\t]/) {\n$thisline .= $lookahead;\n}\nelse {\nlast LINE;\n}\n}\nreturn $thisline;\n}\n\n$lookahead = <STDIN>;       # get first line\nwhile (defined($line = getline())) {\n...\n}\n\nAssigning to a list of private variables to name your arguments:\n\nsub maybeset {\nmy($key, $value) = @;\n$Foo{$key} = $value unless $Foo{$key};\n}\n\nBecause the assignment copies the values, this also has the effect of turning call-by-\nreference into call-by-value.  Otherwise a function is free to do in-place modifications of\n@ and change its caller's values.\n\nupcasein($v1, $v2);  # this changes $v1 and $v2\nsub upcasein {\nfor (@) { tr/a-z/A-Z/ }\n}\n\nYou aren't allowed to modify constants in this way, of course.  If an argument were actually\nliteral and you tried to change it, you'd take a (presumably fatal) exception.   For example,\nthis won't work:\n\nupcasein(\"frederick\");\n\nIt would be much safer if the \"upcasein()\" function were written to return a copy of its\nparameters instead of changing them in place:\n\n($v3, $v4) = upcase($v1, $v2);  # this doesn't change $v1 and $v2\nsub upcase {\nreturn unless defined wantarray;  # void context, do nothing\nmy @parms = @;\nfor (@parms) { tr/a-z/A-Z/ }\nreturn wantarray ? @parms : $parms[0];\n}\n\nNotice how this (unprototyped) function doesn't care whether it was passed real scalars or\narrays.  Perl sees all arguments as one big, long, flat parameter list in @.  This is one\narea where Perl's simple argument-passing style shines.  The \"upcase()\" function would work\nperfectly well without changing the \"upcase()\" definition even if we fed it things like this:\n\n@newlist   = upcase(@list1, @list2);\n@newlist   = upcase( split /:/, $var );\n\nDo not, however, be tempted to do this:\n\n(@a, @b)   = upcase(@list1, @list2);\n\nLike the flattened incoming parameter list, the return list is also flattened on return.  So\nall you have managed to do here is stored everything in @a and made @b empty.  See \"Pass by\nReference\" for alternatives.\n\nA subroutine may be called using an explicit \"&\" prefix.  The \"&\" is optional in modern Perl,\nas are parentheses if the subroutine has been predeclared.  The \"&\" is not optional when just\nnaming the subroutine, such as when it's used as an argument to defined() or undef().  Nor is\nit optional when you want to do an indirect subroutine call with a subroutine name or\nreference using the \"&$subref()\" or \"&{$subref}()\" constructs, although the \"$subref->()\"\nnotation solves that problem.  See perlref for more about all that.\n\nSubroutines may be called recursively.  If a subroutine is called using the \"&\" form, the\nargument list is optional, and if omitted, no @ array is set up for the subroutine: the @\narray at the time of the call is visible to subroutine instead.  This is an efficiency\nmechanism that new users may wish to avoid.\n\n&foo(1,2,3);        # pass three arguments\nfoo(1,2,3);         # the same\n\nfoo();              # pass a null list\n&foo();             # the same\n\n&foo;               # foo() get current args, like foo(@) !!\nuse strict 'subs';\nfoo;                # like foo() iff sub foo predeclared, else\n# a compile-time error\nno strict 'subs';\nfoo;                # like foo() iff sub foo predeclared, else\n# a literal string \"foo\"\n\nNot only does the \"&\" form make the argument list optional, it also disables any prototype\nchecking on arguments you do provide.  This is partly for historical reasons, and partly for\nhaving a convenient way to cheat if you know what you're doing.  See \"Prototypes\" below.\n\nSince Perl 5.16.0, the \"SUB\" token is available under \"use feature 'currentsub'\" and\n\"use 5.16.0\".  It will evaluate to a reference to the currently-running sub, which allows for\nrecursive calls without knowing your subroutine's name.\n\nuse 5.16.0;\nmy $factorial = sub {\nmy ($x) = @;\nreturn 1 if $x == 1;\nreturn($x * SUB->( $x - 1 ) );\n};\n\nThe behavior of \"SUB\" within a regex code block (such as \"/(?{...})/\") is subject to\nchange.\n\nSubroutines whose names are in all upper case are reserved to the Perl core, as are modules\nwhose names are in all lower case.  A subroutine in all capitals is a loosely-held convention\nmeaning it will be called indirectly by the run-time system itself, usually due to a\ntriggered event.  Subroutines whose name start with a left parenthesis are also reserved the\nsame way.  The following is a list of some subroutines that currently do special, pre-defined\nthings.\n\ndocumented later in this document\n\"AUTOLOAD\"\n\ndocumented in perlmod\n\"CLONE\", \"CLONESKIP\"\n\ndocumented in perlobj\n\"DESTROY\", \"DOES\"\n\ndocumented in perltie\n\"BINMODE\", \"CLEAR\", \"CLOSE\", \"DELETE\", \"DESTROY\", \"EOF\", \"EXISTS\", \"EXTEND\", \"FETCH\",\n\"FETCHSIZE\", \"FILENO\", \"FIRSTKEY\", \"GETC\", \"NEXTKEY\", \"OPEN\", \"POP\", \"PRINT\", \"PRINTF\",\n\"PUSH\", \"READ\", \"READLINE\", \"SCALAR\", \"SEEK\", \"SHIFT\", \"SPLICE\", \"STORE\", \"STORESIZE\",\n\"TELL\", \"TIEARRAY\", \"TIEHANDLE\", \"TIEHASH\", \"TIESCALAR\", \"UNSHIFT\", \"UNTIE\", \"WRITE\"\n\ndocumented in PerlIO::via\n\"BINMODE\", \"CLEARERR\", \"CLOSE\", \"EOF\", \"ERROR\", \"FDOPEN\", \"FILENO\", \"FILL\", \"FLUSH\",\n\"OPEN\", \"POPPED\", \"PUSHED\", \"READ\", \"SEEK\", \"SETLINEBUF\", \"SYSOPEN\", \"TELL\", \"UNREAD\",\n\"UTF8\", \"WRITE\"\n\ndocumented in perlfunc\n\"import\" , \"unimport\" , \"INC\"\n\ndocumented in UNIVERSAL\n\"VERSION\"\n\ndocumented in perldebguts\n\"DB::DB\", \"DB::sub\", \"DB::lsub\", \"DB::goto\", \"DB::postponed\"\n\nundocumented, used internally by the overload feature\nany starting with \"(\"\n\nThe \"BEGIN\", \"UNITCHECK\", \"CHECK\", \"INIT\" and \"END\" subroutines are not so much subroutines\nas named special code blocks, of which you can have more than one in a package, and which you\ncan not call explicitly.  See \"BEGIN, UNITCHECK, CHECK, INIT and END\" in perlmod\n",
            "subsections": [
                {
                    "name": "Signatures",
                    "content": "WARNING: Subroutine signatures are experimental.  The feature may be modified or removed in\nfuture versions of Perl.\n\nPerl has an experimental facility to allow a subroutine's formal parameters to be introduced\nby special syntax, separate from the procedural code of the subroutine body.  The formal\nparameter list is known as a signature.  The facility must be enabled first by a pragmatic\ndeclaration, \"use feature 'signatures'\", and it will produce a warning unless the\n\"experimental::signatures\" warnings category is disabled.\n\nThe signature is part of a subroutine's body.  Normally the body of a subroutine is simply a\nbraced block of code, but when using a signature, the signature is a parenthesised list that\ngoes immediately before the block, after any name or attributes.\n\nFor example,\n\nsub foo :lvalue ($a, $b = 1, @c) { .... }\n\nThe signature declares lexical variables that are in scope for the block.  When the\nsubroutine is called, the signature takes control first.  It populates the signature\nvariables from the list of arguments that were passed.  If the argument list doesn't meet the\nrequirements of the signature, then it will throw an exception.  When the signature\nprocessing is complete, control passes to the block.\n\nPositional parameters are handled by simply naming scalar variables in the signature.  For\nexample,\n\nsub foo ($left, $right) {\nreturn $left + $right;\n}\n\ntakes two positional parameters, which must be filled at runtime by two arguments.  By\ndefault the parameters are mandatory, and it is not permitted to pass more arguments than\nexpected.  So the above is equivalent to\n\nsub foo {\ndie \"Too many arguments for subroutine\" unless @ <= 2;\ndie \"Too few arguments for subroutine\" unless @ >= 2;\nmy $left = $[0];\nmy $right = $[1];\nreturn $left + $right;\n}\n\nAn argument can be ignored by omitting the main part of the name from a parameter\ndeclaration, leaving just a bare \"$\" sigil.  For example,\n\nsub foo ($first, $, $third) {\nreturn \"first=$first, third=$third\";\n}\n\nAlthough the ignored argument doesn't go into a variable, it is still mandatory for the\ncaller to pass it.\n\nA positional parameter is made optional by giving a default value, separated from the\nparameter name by \"=\":\n\nsub foo ($left, $right = 0) {\nreturn $left + $right;\n}\n\nThe above subroutine may be called with either one or two arguments.  The default value\nexpression is evaluated when the subroutine is called, so it may provide different default\nvalues for different calls.  It is only evaluated if the argument was actually omitted from\nthe call.  For example,\n\nmy $autoid = 0;\nsub foo ($thing, $id = $autoid++) {\nprint \"$thing has ID $id\";\n}\n\nautomatically assigns distinct sequential IDs to things for which no ID was supplied by the\ncaller.  A default value expression may also refer to parameters earlier in the signature,\nmaking the default for one parameter vary according to the earlier parameters.  For example,\n\nsub foo ($firstname, $surname, $nickname = $firstname) {\nprint \"$firstname $surname is known as \\\"$nickname\\\"\";\n}\n\nAn optional parameter can be nameless just like a mandatory parameter.  For example,\n\nsub foo ($thing, $ = 1) {\nprint $thing;\n}\n\nThe parameter's default value will still be evaluated if the corresponding argument isn't\nsupplied, even though the value won't be stored anywhere.  This is in case evaluating it has\nimportant side effects.  However, it will be evaluated in void context, so if it doesn't have\nside effects and is not trivial it will generate a warning if the \"void\" warning category is\nenabled.  If a nameless optional parameter's default value is not important, it may be\nomitted just as the parameter's name was:\n\nsub foo ($thing, $=) {\nprint $thing;\n}\n\nOptional positional parameters must come after all mandatory positional parameters.  (If\nthere are no mandatory positional parameters then an optional positional parameters can be\nthe first thing in the signature.)  If there are multiple optional positional parameters and\nnot enough arguments are supplied to fill them all, they will be filled from left to right.\n\nAfter positional parameters, additional arguments may be captured in a slurpy parameter.  The\nsimplest form of this is just an array variable:\n\nsub foo ($filter, @inputs) {\nprint $filter->($) foreach @inputs;\n}\n\nWith a slurpy parameter in the signature, there is no upper limit on how many arguments may\nbe passed.  A slurpy array parameter may be nameless just like a positional parameter, in\nwhich case its only effect is to turn off the argument limit that would otherwise apply:\n\nsub foo ($thing, @) {\nprint $thing;\n}\n\nA slurpy parameter may instead be a hash, in which case the arguments available to it are\ninterpreted as alternating keys and values.  There must be as many keys as values: if there\nis an odd argument then an exception will be thrown.  Keys will be stringified, and if there\nare duplicates then the later instance takes precedence over the earlier, as with standard\nhash construction.\n\nsub foo ($filter, %inputs) {\nprint $filter->($, $inputs{$}) foreach sort keys %inputs;\n}\n\nA slurpy hash parameter may be nameless just like other kinds of parameter.  It still insists\nthat the number of arguments available to it be even, even though they're not being put into\na variable.\n\nsub foo ($thing, %) {\nprint $thing;\n}\n\nA slurpy parameter, either array or hash, must be the last thing in the signature.  It may\nfollow mandatory and optional positional parameters; it may also be the only thing in the\nsignature.  Slurpy parameters cannot have default values: if no arguments are supplied for\nthem then you get an empty array or empty hash.\n\nA signature may be entirely empty, in which case all it does is check that the caller passed\nno arguments:\n\nsub foo () {\nreturn 123;\n}\n\nWhen using a signature, the arguments are still available in the special array variable @,\nin addition to the lexical variables of the signature.  There is a difference between the two\nways of accessing the arguments: @ aliases the arguments, but the signature variables get\ncopies of the arguments.  So writing to a signature variable only changes that variable, and\nhas no effect on the caller's variables, but writing to an element of @ modifies whatever\nthe caller used to supply that argument.\n\nThere is a potential syntactic ambiguity between signatures and prototypes (see\n\"Prototypes\"), because both start with an opening parenthesis and both can appear in some of\nthe same places, such as just after the name in a subroutine declaration.  For historical\nreasons, when signatures are not enabled, any opening parenthesis in such a context will\ntrigger very forgiving prototype parsing.  Most signatures will be interpreted as prototypes\nin those circumstances, but won't be valid prototypes.  (A valid prototype cannot contain any\nalphabetic character.)  This will lead to somewhat confusing error messages.\n\nTo avoid ambiguity, when signatures are enabled the special syntax for prototypes is\ndisabled.  There is no attempt to guess whether a parenthesised group was intended to be a\nprototype or a signature.  To give a subroutine a prototype under these circumstances, use a\nprototype attribute.  For example,\n\nsub foo :prototype($) { $[0] }\n\nIt is entirely possible for a subroutine to have both a prototype and a signature.  They do\ndifferent jobs: the prototype affects compilation of calls to the subroutine, and the\nsignature puts argument values into lexical variables at runtime.  You can therefore write\n\nsub foo :prototype($$) ($left, $right) {\nreturn $left + $right;\n}\n\nThe prototype attribute, and any other attributes, must come before the signature.  The\nsignature always immediately precedes the block of the subroutine's body.\n"
                },
                {
                    "name": "Private Variables via my()",
                    "content": "Synopsis:\n\nmy $foo;            # declare $foo lexically local\nmy (@wid, %get);    # declare list of variables local\nmy $foo = \"flurp\";  # declare $foo lexical, and init it\nmy @oof = @bar;     # declare @oof lexical, and init it\nmy $x : Foo = $y;   # similar, with an attribute applied\n\nWARNING: The use of attribute lists on \"my\" declarations is still evolving.  The current\nsemantics and interface are subject to change.  See attributes and Attribute::Handlers.\n\nThe \"my\" operator declares the listed variables to be lexically confined to the enclosing\nblock, conditional (\"if\"/\"unless\"/\"elsif\"/\"else\"), loop\n(\"for\"/\"foreach\"/\"while\"/\"until\"/\"continue\"), subroutine, \"eval\", or \"do\"/\"require\"/\"use\"'d\nfile.  If more than one value is listed, the list must be placed in parentheses.  All listed\nelements must be legal lvalues.  Only alphanumeric identifiers may be lexically\nscoped--magical built-ins like $/ must currently be \"local\"ized with \"local\" instead.\n\nUnlike dynamic variables created by the \"local\" operator, lexical variables declared with\n\"my\" are totally hidden from the outside world, including any called subroutines.  This is\ntrue if it's the same subroutine called from itself or elsewhere--every call gets its own\ncopy.\n\nThis doesn't mean that a \"my\" variable declared in a statically enclosing lexical scope would\nbe invisible.  Only dynamic scopes are cut off.   For example, the \"bumpx()\" function below\nhas access to the lexical $x variable because both the \"my\" and the \"sub\" occurred at the\nsame scope, presumably file scope.\n\nmy $x = 10;\nsub bumpx { $x++ }\n\nAn \"eval()\", however, can see lexical variables of the scope it is being evaluated in, so\nlong as the names aren't hidden by declarations within the \"eval()\" itself.  See perlref.\n\nThe parameter list to my() may be assigned to if desired, which allows you to initialize your\nvariables.  (If no initializer is given for a particular variable, it is created with the\nundefined value.)  Commonly this is used to name input parameters to a subroutine.  Examples:\n\n$arg = \"fred\";        # \"global\" variable\n$n = cuberoot(27);\nprint \"$arg thinks the root is $n\\n\";\nfred thinks the root is 3\n\nsub cuberoot {\nmy $arg = shift;  # name doesn't matter\n$arg = 1/3;\nreturn $arg;\n}\n\nThe \"my\" is simply a modifier on something you might assign to.  So when you do assign to\nvariables in its argument list, \"my\" doesn't change whether those variables are viewed as a\nscalar or an array.  So\n\nmy ($foo) = <STDIN>;                # WRONG?\nmy @FOO = <STDIN>;\n\nboth supply a list context to the right-hand side, while\n\nmy $foo = <STDIN>;\n\nsupplies a scalar context.  But the following declares only one variable:\n\nmy $foo, $bar = 1;                  # WRONG\n\nThat has the same effect as\n\nmy $foo;\n$bar = 1;\n\nThe declared variable is not introduced (is not visible) until after the current statement.\nThus,\n\nmy $x = $x;\n\ncan be used to initialize a new $x with the value of the old $x, and the expression\n\nmy $x = 123 and $x == 123\n\nis false unless the old $x happened to have the value 123.\n\nLexical scopes of control structures are not bounded precisely by the braces that delimit\ntheir controlled blocks; control expressions are part of that scope, too.  Thus in the loop\n\nwhile (my $line = <>) {\n$line = lc $line;\n} continue {\nprint $line;\n}\n\nthe scope of $line extends from its declaration throughout the rest of the loop construct\n(including the \"continue\" clause), but not beyond it.  Similarly, in the conditional\n\nif ((my $answer = <STDIN>) =~ /^yes$/i) {\nuseragrees();\n} elsif ($answer =~ /^no$/i) {\nuserdisagrees();\n} else {\nchomp $answer;\ndie \"'$answer' is neither 'yes' nor 'no'\";\n}\n\nthe scope of $answer extends from its declaration through the rest of that conditional,\nincluding any \"elsif\" and \"else\" clauses, but not beyond it.  See \"Simple Statements\" in\nperlsyn for information on the scope of variables in statements with modifiers.\n\nThe \"foreach\" loop defaults to scoping its index variable dynamically in the manner of\n\"local\".  However, if the index variable is prefixed with the keyword \"my\", or if there is\nalready a lexical by that name in scope, then a new lexical is created instead.  Thus in the\nloop\n\nfor my $i (1, 2, 3) {\nsomefunction();\n}\n\nthe scope of $i extends to the end of the loop, but not beyond it, rendering the value of $i\ninaccessible within \"somefunction()\".\n\nSome users may wish to encourage the use of lexically scoped variables.  As an aid to\ncatching implicit uses to package variables, which are always global, if you say\n\nuse strict 'vars';\n\nthen any variable mentioned from there to the end of the enclosing block must either refer to\na lexical variable, be predeclared via \"our\" or \"use vars\", or else must be fully qualified\nwith the package name.  A compilation error results otherwise.  An inner block may\ncountermand this with \"no strict 'vars'\".\n\nA \"my\" has both a compile-time and a run-time effect.  At compile time, the compiler takes\nnotice of it.  The principal usefulness of this is to quiet \"use strict 'vars'\", but it is\nalso essential for generation of closures as detailed in perlref.  Actual initialization is\ndelayed until run time, though, so it gets executed at the appropriate time, such as each\ntime through a loop, for example.\n\nVariables declared with \"my\" are not part of any package and are therefore never fully\nqualified with the package name.  In particular, you're not allowed to try to make a package\nvariable (or other global) lexical:\n\nmy $pack::var;      # ERROR!  Illegal syntax\n\nIn fact, a dynamic variable (also known as package or global variables) are still accessible\nusing the fully qualified \"::\" notation even while a lexical of the same name is also\nvisible:\n\npackage main;\nlocal $x = 10;\nmy    $x = 20;\nprint \"$x and $::x\\n\";\n\nThat will print out 20 and 10.\n\nYou may declare \"my\" variables at the outermost scope of a file to hide any such identifiers\nfrom the world outside that file.  This is similar in spirit to C's static variables when\nthey are used at the file level.  To do this with a subroutine requires the use of a closure\n(an anonymous function that accesses enclosing lexicals).  If you want to create a private\nsubroutine that cannot be called from outside that block, it can declare a lexical variable\ncontaining an anonymous sub reference:\n\nmy $secretversion = '1.001-beta';\nmy $secretsub = sub { print $secretversion };\n&$secretsub();\n\nAs long as the reference is never returned by any function within the module, no outside\nmodule can see the subroutine, because its name is not in any package's symbol table.\nRemember that it's not REALLY called $somepack::secretversion or anything; it's just\n$secretversion, unqualified and unqualifiable.\n\nThis does not work with object methods, however; all object methods have to be in the symbol\ntable of some package to be found.  See \"Function Templates\" in perlref for something of a\nwork-around to this.\n"
                },
                {
                    "name": "Persistent Private Variables",
                    "content": "There are two ways to build persistent private variables in Perl 5.10.  First, you can simply\nuse the \"state\" feature.  Or, you can use closures, if you want to stay compatible with\nreleases older than 5.10.\n\nPersistent variables via ssttaattee(())\n\nBeginning with Perl 5.10.0, you can declare variables with the \"state\" keyword in place of\n\"my\".  For that to work, though, you must have enabled that feature beforehand, either by\nusing the \"feature\" pragma, or by using \"-E\" on one-liners (see feature).  Beginning with\nPerl 5.16, the \"CORE::state\" form does not require the \"feature\" pragma.\n\nThe \"state\" keyword creates a lexical variable (following the same scoping rules as \"my\")\nthat persists from one subroutine call to the next.  If a state variable resides inside an\nanonymous subroutine, then each copy of the subroutine has its own copy of the state\nvariable.  However, the value of the state variable will still persist between calls to the\nsame copy of the anonymous subroutine.  (Don't forget that \"sub { ... }\" creates a new\nsubroutine each time it is executed.)\n\nFor example, the following code maintains a private counter, incremented each time the\ngimmeanother() function is called:\n\nuse feature 'state';\nsub gimmeanother { state $x; return ++$x }\n\nAnd this example uses anonymous subroutines to create separate counters:\n\nuse feature 'state';\nsub createcounter {\nreturn sub { state $x; return ++$x }\n}\n\nAlso, since $x is lexical, it can't be reached or modified by any Perl code outside.\n\nWhen combined with variable declaration, simple assignment to \"state\" variables (as in \"state\n$x = 42\") is executed only the first time.  When such statements are evaluated subsequent\ntimes, the assignment is ignored.  The behavior of assignment to \"state\" declarations where\nthe left hand side of the assignment involves any parentheses is currently undefined.\n\nPersistent variables with closures\n\nJust because a lexical variable is lexically (also called statically) scoped to its enclosing\nblock, \"eval\", or \"do\" FILE, this doesn't mean that within a function it works like a C\nstatic.  It normally works more like a C auto, but with implicit garbage collection.\n\nUnlike local variables in C or C++, Perl's lexical variables don't necessarily get recycled\njust because their scope has exited.  If something more permanent is still aware of the\nlexical, it will stick around.  So long as something else references a lexical, that lexical\nwon't be freed--which is as it should be.  You wouldn't want memory being free until you were\ndone using it, or kept around once you were done.  Automatic garbage collection takes care of\nthis for you.\n\nThis means that you can pass back or save away references to lexical variables, whereas to\nreturn a pointer to a C auto is a grave error.  It also gives us a way to simulate C's\nfunction statics.  Here's a mechanism for giving a function private variables with both\nlexical scoping and a static lifetime.  If you do want to create something like C's static\nvariables, just enclose the whole function in an extra block, and put the static variable\noutside the function but in the block.\n\n{\nmy $secretval = 0;\nsub gimmeanother {\nreturn ++$secretval;\n}\n}\n# $secretval now becomes unreachable by the outside\n# world, but retains its value between calls to gimmeanother\n\nIf this function is being sourced in from a separate file via \"require\" or \"use\", then this\nis probably just fine.  If it's all in the main program, you'll need to arrange for the \"my\"\nto be executed early, either by putting the whole block above your main program, or more\nlikely, placing merely a \"BEGIN\" code block around it to make sure it gets executed before\nyour program starts to run:\n\nBEGIN {\nmy $secretval = 0;\nsub gimmeanother {\nreturn ++$secretval;\n}\n}\n\nSee \"BEGIN, UNITCHECK, CHECK, INIT and END\" in perlmod about the special triggered code\nblocks, \"BEGIN\", \"UNITCHECK\", \"CHECK\", \"INIT\" and \"END\".\n\nIf declared at the outermost scope (the file scope), then lexicals work somewhat like C's\nfile statics.  They are available to all functions in that same file declared below them, but\nare inaccessible from outside that file.  This strategy is sometimes used in modules to\ncreate private variables that the whole module can see.\n"
                },
                {
                    "name": "Temporary Values via local()",
                    "content": "WARNING: In general, you should be using \"my\" instead of \"local\", because it's faster and\nsafer.  Exceptions to this include the global punctuation variables, global filehandles and\nformats, and direct manipulation of the Perl symbol table itself.  \"local\" is mostly used\nwhen the current value of a variable must be visible to called subroutines.\n\nSynopsis:\n\n# localization of values\n\nlocal $foo;                # make $foo dynamically local\nlocal (@wid, %get);        # make list of variables local\nlocal $foo = \"flurp\";      # make $foo dynamic, and init it\nlocal @oof = @bar;         # make @oof dynamic, and init it\n\nlocal $hash{key} = \"val\";  # sets a local value for this hash entry\ndelete local $hash{key};   # delete this entry for the current block\nlocal ($cond ? $v1 : $v2); # several types of lvalues support\n# localization\n\n# localization of symbols\n\nlocal *FH;                 # localize $FH, @FH, %FH, &FH  ...\nlocal *merlyn = *randal;   # now $merlyn is really $randal, plus\n#     @merlyn is really @randal, etc\nlocal *merlyn = 'randal';  # SAME THING: promote 'randal' to *randal\nlocal *merlyn = \\$randal;  # just alias $merlyn, not @merlyn etc\n\nA \"local\" modifies its listed variables to be \"local\" to the enclosing block, \"eval\", or \"do\nFILE\"--and to any subroutine called from within that block.  A \"local\" just gives temporary\nvalues to global (meaning package) variables.  It does not create a local variable.  This is\nknown as dynamic scoping.  Lexical scoping is done with \"my\", which works more like C's auto\ndeclarations.\n\nSome types of lvalues can be localized as well: hash and array elements and slices,\nconditionals (provided that their result is always localizable), and symbolic references.  As\nfor simple variables, this creates new, dynamically scoped values.\n\nIf more than one variable or expression is given to \"local\", they must be placed in\nparentheses.  This operator works by saving the current values of those variables in its\nargument list on a hidden stack and restoring them upon exiting the block, subroutine, or\neval.  This means that called subroutines can also reference the local variable, but not the\nglobal one.  The argument list may be assigned to if desired, which allows you to initialize\nyour local variables.  (If no initializer is given for a particular variable, it is created\nwith an undefined value.)\n\nBecause \"local\" is a run-time operator, it gets executed each time through a loop.\nConsequently, it's more efficient to localize your variables outside the loop.\n\nGrammatical note on llooccaall(())\n\nA \"local\" is simply a modifier on an lvalue expression.  When you assign to a \"local\"ized\nvariable, the \"local\" doesn't change whether its list is viewed as a scalar or an array.  So\n\nlocal($foo) = <STDIN>;\nlocal @FOO = <STDIN>;\n\nboth supply a list context to the right-hand side, while\n\nlocal $foo = <STDIN>;\n\nsupplies a scalar context.\n\nLocalization of special variables\n\nIf you localize a special variable, you'll be giving a new value to it, but its magic won't\ngo away.  That means that all side-effects related to this magic still work with the\nlocalized value.\n\nThis feature allows code like this to work :\n\n# Read the whole contents of FILE in $slurp\n{ local $/ = undef; $slurp = <FILE>; }\n\nNote, however, that this restricts localization of some values ; for example, the following\nstatement dies, as of perl 5.10.0, with an error Modification of a read-only value attempted,\nbecause the $1 variable is magical and read-only :\n\nlocal $1 = 2;\n\nOne exception is the default scalar variable: starting with perl 5.14 \"local($)\" will always\nstrip all magic from $, to make it possible to safely reuse $ in a subroutine.\n\nWARNING: Localization of tied arrays and hashes does not currently work as described.  This\nwill be fixed in a future release of Perl; in the meantime, avoid code that relies on any\nparticular behavior of localising tied arrays or hashes (localising individual elements is\nstill okay).  See \"Localising Tied Arrays and Hashes Is Broken\" in perl58delta for more\ndetails.\n\nLocalization of globs\n\nThe construct\n\nlocal *name;\n\ncreates a whole new symbol table entry for the glob \"name\" in the current package.  That\nmeans that all variables in its glob slot ($name, @name, %name, &name, and the \"name\"\nfilehandle) are dynamically reset.\n\nThis implies, among other things, that any magic eventually carried by those variables is\nlocally lost.  In other words, saying \"local */\" will not have any effect on the internal\nvalue of the input record separator.\n\nLocalization of elements of composite types\n\nIt's also worth taking a moment to explain what happens when you \"local\"ize a member of a\ncomposite type (i.e. an array or hash element).  In this case, the element is \"local\"ized by\nname.  This means that when the scope of the \"local()\" ends, the saved value will be restored\nto the hash element whose key was named in the \"local()\", or the array element whose index\nwas named in the \"local()\".  If that element was deleted while the \"local()\" was in effect\n(e.g. by a \"delete()\" from a hash or a \"shift()\" of an array), it will spring back into\nexistence, possibly extending an array and filling in the skipped elements with \"undef\".  For\ninstance, if you say\n\n%hash = ( 'This' => 'is', 'a' => 'test' );\n@ary  = ( 0..5 );\n{\nlocal($ary[5]) = 6;\nlocal($hash{'a'}) = 'drill';\nwhile (my $e = pop(@ary)) {\nprint \"$e . . .\\n\";\nlast unless $e > 3;\n}\nif (@ary) {\n$hash{'only a'} = 'test';\ndelete $hash{'a'};\n}\n}\nprint join(' ', map { \"$ $hash{$}\" } sort keys %hash),\".\\n\";\nprint \"The array has \",scalar(@ary),\" elements: \",\njoin(', ', map { defined $ ? $ : 'undef' } @ary),\"\\n\";\n\nPerl will print\n\n6 . . .\n4 . . .\n3 . . .\nThis is a test only a test.\nThe array has 6 elements: 0, 1, 2, undef, undef, 5\n\nThe behavior of local() on non-existent members of composite types is subject to change in\nfuture. The behavior of local() on array elements specified using negative indexes is\nparticularly surprising, and is very likely to change.\n\nLocalized deletion of elements of composite types\n\nYou can use the \"delete local $array[$idx]\" and \"delete local $hash{key}\" constructs to\ndelete a composite type entry for the current block and restore it when it ends.  They return\nthe array/hash value before the localization, which means that they are respectively\nequivalent to\n\ndo {\nmy $val = $array[$idx];\nlocal  $array[$idx];\ndelete $array[$idx];\n$val\n}\n\nand\n\ndo {\nmy $val = $hash{key};\nlocal  $hash{key};\ndelete $hash{key};\n$val\n}\n\nexcept that for those the \"local\" is scoped to the \"do\" block.  Slices are also accepted.\n\nmy %hash = (\na => [ 7, 8, 9 ],\nb => 1,\n)\n\n{\nmy $a = delete local $hash{a};\n# $a is [ 7, 8, 9 ]\n# %hash is (b => 1)\n\n{\nmy @nums = delete local @$a[0, 2]\n# @nums is (7, 9)\n# $a is [ undef, 8 ]\n\n$a[0] = 999; # will be erased when the scope ends\n}\n# $a is back to [ 7, 8, 9 ]\n\n}\n# %hash is back to its original state\n\nThis construct is supported since Perl v5.12.\n"
                },
                {
                    "name": "Lvalue subroutines",
                    "content": "It is possible to return a modifiable value from a subroutine.  To do this, you have to\ndeclare the subroutine to return an lvalue.\n\nmy $val;\nsub canmod : lvalue {\n$val;  # or:  return $val;\n}\nsub nomod {\n$val;\n}\n\ncanmod() = 5;   # assigns to $val\nnomod()  = 5;   # ERROR\n\nThe scalar/list context for the subroutine and for the right-hand side of assignment is\ndetermined as if the subroutine call is replaced by a scalar.  For example, consider:\n\ndata(2,3) = getdata(3,4);\n\nBoth subroutines here are called in a scalar context, while in:\n\n(data(2,3)) = getdata(3,4);\n\nand in:\n\n(data(2),data(3)) = getdata(3,4);\n\nall the subroutines are called in a list context.\n\nLvalue subroutines are convenient, but you have to keep in mind that, when used with objects,\nthey may violate encapsulation.  A normal mutator can check the supplied argument before\nsetting the attribute it is protecting, an lvalue subroutine cannot.  If you require any\nspecial processing when storing and retrieving the values, consider using the CPAN module\nSentinel or something similar.\n"
                },
                {
                    "name": "Lexical Subroutines",
                    "content": "Beginning with Perl 5.18, you can declare a private subroutine with \"my\" or \"state\".  As with\nstate variables, the \"state\" keyword is only available under \"use feature 'state'\" or \"use\n5.010\" or higher.\n\nPrior to Perl 5.26, lexical subroutines were deemed experimental and were available only\nunder the \"use feature 'lexicalsubs'\" pragma.  They also produced a warning unless the\n\"experimental::lexicalsubs\" warnings category was disabled.\n\nThese subroutines are only visible within the block in which they are declared, and only\nafter that declaration:\n\n# Include these two lines if your code is intended to run under Perl\n# versions earlier than 5.26.\nno warnings \"experimental::lexicalsubs\";\nuse feature 'lexicalsubs';\n\nfoo();              # calls the package/global subroutine\nstate sub foo {\nfoo();          # also calls the package subroutine\n}\nfoo();              # calls \"state\" sub\nmy $ref = \\&foo;    # take a reference to \"state\" sub\n\nmy sub bar { ... }\nbar();              # calls \"my\" sub\n\nYou can't (directly) write a recursive lexical subroutine:\n\n# WRONG\nmy sub baz {\nbaz();\n}\n\nThis example fails because \"baz()\" refers to the package/global subroutine \"baz\", not the\nlexical subroutine currently being defined.\n\nThe solution is to use \"SUB\":\n\nmy sub baz {\nSUB->();    # calls itself\n}\n\nIt is possible to predeclare a lexical subroutine.  The \"sub foo {...}\" subroutine definition\nsyntax respects any previous \"my sub;\" or \"state sub;\" declaration.  Using this to define\nrecursive subroutines is a bad idea, however:\n\nmy sub baz;         # predeclaration\nsub baz {           # define the \"my\" sub\nbaz();          # WRONG: calls itself, but leaks memory\n}\n\nJust like \"my $f; $f = sub { $f->() }\", this example leaks memory.  The name \"baz\" is a\nreference to the subroutine, and the subroutine uses the name \"baz\"; they keep each other\nalive (see \"Circular References\" in perlref).\n\n\"state sub\" vs \"my sub\"\n\nWhat is the difference between \"state\" subs and \"my\" subs?  Each time that execution enters a\nblock when \"my\" subs are declared, a new copy of each sub is created.  \"State\" subroutines\npersist from one execution of the containing block to the next.\n\nSo, in general, \"state\" subroutines are faster.  But \"my\" subs are necessary if you want to\ncreate closures:\n\nsub whatever {\nmy $x = shift;\nmy sub inner {\n... do something with $x ...\n}\ninner();\n}\n\nIn this example, a new $x is created when \"whatever\" is called, and also a new \"inner\", which\ncan see the new $x.  A \"state\" sub will only see the $x from the first call to \"whatever\".\n\n\"our\" subroutines\n\nLike \"our $variable\", \"our sub\" creates a lexical alias to the package subroutine of the same\nname.\n\nThe two main uses for this are to switch back to using the package sub inside an inner scope:\n\nsub foo { ... }\n\nsub bar {\nmy sub foo { ... }\n{\n# need to use the outer foo here\nour sub foo;\nfoo();\n}\n}\n\nand to make a subroutine visible to other packages in the same scope:\n\npackage MySneakyModule;\n\nour sub dosomething { ... }\n\nsub dosomethingwithcaller {\npackage DB;\n() = caller 1;          # sets @DB::args\ndosomething(@args);    # uses MySneakyModule::dosomething\n}\n"
                },
                {
                    "name": "Passing Symbol Table Entries (typeglobs)",
                    "content": "WARNING: The mechanism described in this section was originally the only way to simulate\npass-by-reference in older versions of Perl.  While it still works fine in modern versions,\nthe new reference mechanism is generally easier to work with.  See below.\n\nSometimes you don't want to pass the value of an array to a subroutine but rather the name of\nit, so that the subroutine can modify the global copy of it rather than working with a local\ncopy.  In perl you can refer to all objects of a particular name by prefixing the name with a\nstar: *foo.  This is often known as a \"typeglob\", because the star on the front can be\nthought of as a wildcard match for all the funny prefix characters on variables and\nsubroutines and such.\n\nWhen evaluated, the typeglob produces a scalar value that represents all the objects of that\nname, including any filehandle, format, or subroutine.  When assigned to, it causes the name\nmentioned to refer to whatever \"*\" value was assigned to it.  Example:\n\nsub doubleary {\nlocal(*someary) = @;\nforeach $elem (@someary) {\n$elem *= 2;\n}\n}\ndoubleary(*foo);\ndoubleary(*bar);\n\nScalars are already passed by reference, so you can modify scalar arguments without using\nthis mechanism by referring explicitly to $[0] etc.  You can modify all the elements of an\narray by passing all the elements as scalars, but you have to use the \"*\" mechanism (or the\nequivalent reference mechanism) to \"push\", \"pop\", or change the size of an array.  It will\ncertainly be faster to pass the typeglob (or reference).\n\nEven if you don't want to modify an array, this mechanism is useful for passing multiple\narrays in a single LIST, because normally the LIST mechanism will merge all the array values\nso that you can't extract out the individual arrays.  For more on typeglobs, see \"Typeglobs\nand Filehandles\" in perldata.\n"
                },
                {
                    "name": "When to Still Use local()",
                    "content": "Despite the existence of \"my\", there are still three places where the \"local\" operator still\nshines.  In fact, in these three places, you must use \"local\" instead of \"my\".\n\n1.  You need to give a global variable a temporary value, especially $.\n\nThe global variables, like @ARGV or the punctuation variables, must be \"local\"ized with\n\"local()\".  This block reads in /etc/motd, and splits it up into chunks separated by\nlines of equal signs, which are placed in @Fields.\n\n{\nlocal @ARGV = (\"/etc/motd\");\nlocal $/ = undef;\nlocal $ = <>;\n@Fields = split /^\\s*=+\\s*$/;\n}\n\nIt particular, it's important to \"local\"ize $ in any routine that assigns to it.  Look\nout for implicit assignments in \"while\" conditionals.\n\n2.  You need to create a local file or directory handle or a local function.\n\nA function that needs a filehandle of its own must use \"local()\" on a complete typeglob.\nThis can be used to create new symbol table entries:\n\nsub ioqueue {\nlocal  (*READER, *WRITER);    # not my!\npipe    (READER,  WRITER)     or die \"pipe: $!\";\nreturn (*READER, *WRITER);\n}\n($head, $tail) = ioqueue();\n\nSee the Symbol module for a way to create anonymous symbol table entries.\n\nBecause assignment of a reference to a typeglob creates an alias, this can be used to\ncreate what is effectively a local function, or at least, a local alias.\n\n{\nlocal *grow = \\&shrink; # only until this block exits\ngrow();                # really calls shrink()\nmove();                # if move() grow()s, it shrink()s too\n}\ngrow();                    # get the real grow() again\n\nSee \"Function Templates\" in perlref for more about manipulating functions by name in this\nway.\n\n3.  You want to temporarily change just one element of an array or hash.\n\nYou can \"local\"ize just one element of an aggregate.  Usually this is done on dynamics:\n\n{\nlocal $SIG{INT} = 'IGNORE';\nfunct();                            # uninterruptible\n}\n# interruptibility automatically restored here\n\nBut it also works on lexically declared aggregates.\n"
                },
                {
                    "name": "Pass by Reference",
                    "content": "If you want to pass more than one array or hash into a function--or return them from it--and\nhave them maintain their integrity, then you're going to have to use an explicit pass-by-\nreference.  Before you do that, you need to understand references as detailed in perlref.\nThis section may not make much sense to you otherwise.\n\nHere are a few simple examples.  First, let's pass in several arrays to a function and have\nit \"pop\" all of then, returning a new list of all their former last elements:\n\n@tailings = popmany ( \\@a, \\@b, \\@c, \\@d );\n\nsub popmany {\nmy $aref;\nmy @retlist;\nforeach $aref ( @ ) {\npush @retlist, pop @$aref;\n}\nreturn @retlist;\n}\n\nHere's how you might write a function that returns a list of keys occurring in all the hashes\npassed to it:\n\n@common = inter( \\%foo, \\%bar, \\%joe );\nsub inter {\nmy ($k, $href, %seen); # locals\nforeach $href (@) {\nwhile ( $k = each %$href ) {\n$seen{$k}++;\n}\n}\nreturn grep { $seen{$} == @ } keys %seen;\n}\n\nSo far, we're using just the normal list return mechanism.  What happens if you want to pass\nor return a hash?  Well, if you're using only one of them, or you don't mind them\nconcatenating, then the normal calling convention is ok, although a little expensive.\n\nWhere people get into trouble is here:\n\n(@a, @b) = func(@c, @d);\nor\n(%a, %b) = func(%c, %d);\n\nThat syntax simply won't work.  It sets just @a or %a and clears the @b or %b.  Plus the\nfunction didn't get passed into two separate arrays or hashes: it got one long list in @, as\nalways.\n\nIf you can arrange for everyone to deal with this through references, it's cleaner code,\nalthough not so nice to look at.  Here's a function that takes two array references as\narguments, returning the two array elements in order of how many elements they have in them:\n\n($aref, $bref) = func(\\@c, \\@d);\nprint \"@$aref has more than @$bref\\n\";\nsub func {\nmy ($cref, $dref) = @;\nif (@$cref > @$dref) {\nreturn ($cref, $dref);\n} else {\nreturn ($dref, $cref);\n}\n}\n\nIt turns out that you can actually do this also:\n\n(*a, *b) = func(\\@c, \\@d);\nprint \"@a has more than @b\\n\";\nsub func {\nlocal (*c, *d) = @;\nif (@c > @d) {\nreturn (\\@c, \\@d);\n} else {\nreturn (\\@d, \\@c);\n}\n}\n\nHere we're using the typeglobs to do symbol table aliasing.  It's a tad subtle, though, and\nalso won't work if you're using \"my\" variables, because only globals (even in disguise as\n\"local\"s) are in the symbol table.\n\nIf you're passing around filehandles, you could usually just use the bare typeglob, like\n*STDOUT, but typeglobs references work, too.  For example:\n\nsplutter(\\*STDOUT);\nsub splutter {\nmy $fh = shift;\nprint $fh \"her um well a hmmm\\n\";\n}\n\n$rec = getrec(\\*STDIN);\nsub getrec {\nmy $fh = shift;\nreturn scalar <$fh>;\n}\n\nIf you're planning on generating new filehandles, you could do this.  Notice to pass back\njust the bare *FH, not its reference.\n\nsub openit {\nmy $path = shift;\nlocal *FH;\nreturn open (FH, $path) ? *FH : undef;\n}\n"
                },
                {
                    "name": "Prototypes",
                    "content": "Perl supports a very limited kind of compile-time argument checking using function\nprototyping.  This can be declared in either the PROTO section or with a prototype attribute.\nIf you declare either of\n\nsub mypush (\\@@)\nsub mypush :prototype(\\@@)\n\nthen \"mypush()\" takes arguments exactly like \"push()\" does.\n\nIf subroutine signatures are enabled (see \"Signatures\"), then the shorter PROTO syntax is\nunavailable, because it would clash with signatures.  In that case, a prototype can only be\ndeclared in the form of an attribute.\n\nThe function declaration must be visible at compile time.  The prototype affects only\ninterpretation of new-style calls to the function, where new-style is defined as not using\nthe \"&\" character.  In other words, if you call it like a built-in function, then it behaves\nlike a built-in function.  If you call it like an old-fashioned subroutine, then it behaves\nlike an old-fashioned subroutine.  It naturally falls out from this rule that prototypes have\nno influence on subroutine references like \"\\&foo\" or on indirect subroutine calls like\n\"&{$subref}\" or \"$subref->()\".\n\nMethod calls are not influenced by prototypes either, because the function to be called is\nindeterminate at compile time, since the exact code called depends on inheritance.\n\nBecause the intent of this feature is primarily to let you define subroutines that work like\nbuilt-in functions, here are prototypes for some other functions that parse almost exactly\nlike the corresponding built-in.\n\nDeclared as             Called as\n\nsub mylink ($$)         mylink $old, $new\nsub myvec ($$$)         myvec $var, $offset, 1\nsub myindex ($$;$)      myindex &getstring, \"substr\"\nsub mysyswrite ($$$;$)  mysyswrite $buf, 0, length($buf) - $off, $off\nsub myreverse (@)       myreverse $a, $b, $c\nsub myjoin ($@)         myjoin \":\", $a, $b, $c\nsub mypop (\\@)          mypop @array\nsub mysplice (\\@$$@)    mysplice @array, 0, 2, @pushme\nsub mykeys (\\[%@])      mykeys $hashref->%*\nsub myopen (*;$)        myopen HANDLE, $name\nsub mypipe ()         mypipe READHANDLE, WRITEHANDLE\nsub mygrep (&@)         mygrep { /foo/ } $a, $b, $c\nsub myrand (;$)         myrand 42\nsub mytime ()           mytime\n\nAny backslashed prototype character represents an actual argument that must start with that\ncharacter (optionally preceded by \"my\", \"our\" or \"local\"), with the exception of \"$\", which\nwill accept any scalar lvalue expression, such as \"$foo = 7\" or \"myfunction()->[0]\".  The\nvalue passed as part of @ will be a reference to the actual argument given in the subroutine\ncall, obtained by applying \"\\\" to that argument.\n\nYou can use the \"\\[]\" backslash group notation to specify more than one allowed argument\ntype.  For example:\n\nsub myref (\\[$@%&*])\n\nwill allow calling myref() as\n\nmyref $var\nmyref @array\nmyref %hash\nmyref &sub\nmyref *glob\n\nand the first argument of myref() will be a reference to a scalar, an array, a hash, a code,\nor a glob.\n\nUnbackslashed prototype characters have special meanings.  Any unbackslashed \"@\" or \"%\" eats\nall remaining arguments, and forces list context.  An argument represented by \"$\" forces\nscalar context.  An \"&\" requires an anonymous subroutine, which, if passed as the first\nargument, does not require the \"sub\" keyword or a subsequent comma.\n\nA \"*\" allows the subroutine to accept a bareword, constant, scalar expression, typeglob, or a\nreference to a typeglob in that slot.  The value will be available to the subroutine either\nas a simple scalar, or (in the latter two cases) as a reference to the typeglob.  If you wish\nto always convert such arguments to a typeglob reference, use Symbol::qualifytoref() as\nfollows:\n\nuse Symbol 'qualifytoref';\n\nsub foo (*) {\nmy $fh = qualifytoref(shift, caller);\n...\n}\n\nThe \"+\" prototype is a special alternative to \"$\" that will act like \"\\[@%]\" when given a\nliteral array or hash variable, but will otherwise force scalar context on the argument.\nThis is useful for functions which should accept either a literal array or an array reference\nas the argument:\n\nsub mypush (+@) {\nmy $aref = shift;\ndie \"Not an array or arrayref\" unless ref $aref eq 'ARRAY';\npush @$aref, @;\n}\n\nWhen using the \"+\" prototype, your function must check that the argument is of an acceptable\ntype.\n\nA semicolon (\";\") separates mandatory arguments from optional arguments.  It is redundant\nbefore \"@\" or \"%\", which gobble up everything else.\n\nAs the last character of a prototype, or just before a semicolon, a \"@\" or a \"%\", you can use\n\"\" in place of \"$\": if this argument is not provided, $ will be used instead.\n\nNote how the last three examples in the table above are treated specially by the parser.\n\"mygrep()\" is parsed as a true list operator, \"myrand()\" is parsed as a true unary operator\nwith unary precedence the same as \"rand()\", and \"mytime()\" is truly without arguments, just\nlike \"time()\".  That is, if you say\n\nmytime +2;\n\nyou'll get \"mytime() + 2\", not mytime(2), which is how it would be parsed without a\nprototype.  If you want to force a unary function to have the same precedence as a list\noperator, add \";\" to the end of the prototype:\n\nsub mygetprotobynumber($;);\nmygetprotobynumber $a > $b; # parsed as mygetprotobynumber($a > $b)\n\nThe interesting thing about \"&\" is that you can generate new syntax with it, provided it's in\nthe initial position:\n\nsub try (&@) {\nmy($try,$catch) = @;\neval { &$try };\nif ($@) {\nlocal $ = $@;\n&$catch;\n}\n}\nsub catch (&) { $[0] }\n\ntry {\ndie \"phooey\";\n} catch {\n/phooey/ and print \"unphooey\\n\";\n};\n\nThat prints \"unphooey\".  (Yes, there are still unresolved issues having to do with visibility\nof @.  I'm ignoring that question for the moment.  (But note that if we make @ lexically\nscoped, those anonymous subroutines can act like closures... (Gee, is this sounding a little\nLispish?  (Never mind.))))\n\nAnd here's a reimplementation of the Perl \"grep\" operator:\n\nsub mygrep (&@) {\nmy $code = shift;\nmy @result;\nforeach $ (@) {\npush(@result, $) if &$code;\n}\n@result;\n}\n\nSome folks would prefer full alphanumeric prototypes.  Alphanumerics have been intentionally\nleft out of prototypes for the express purpose of someday in the future adding named, formal\nparameters.  The current mechanism's main goal is to let module writers provide better\ndiagnostics for module users.  Larry feels the notation quite understandable to Perl\nprogrammers, and that it will not intrude greatly upon the meat of the module, nor make it\nharder to read.  The line noise is visually encapsulated into a small pill that's easy to\nswallow.\n\nIf you try to use an alphanumeric sequence in a prototype you will generate an optional\nwarning - \"Illegal character in prototype...\".  Unfortunately earlier versions of Perl\nallowed the prototype to be used as long as its prefix was a valid prototype.  The warning\nmay be upgraded to a fatal error in a future version of Perl once the majority of offending\ncode is fixed.\n\nIt's probably best to prototype new functions, not retrofit prototyping into older ones.\nThat's because you must be especially careful about silent impositions of differing list\nversus scalar contexts.  For example, if you decide that a function should take just one\nparameter, like this:\n\nsub func ($) {\nmy $n = shift;\nprint \"you gave me $n\\n\";\n}\n\nand someone has been calling it with an array or expression returning a list:\n\nfunc(@foo);\nfunc( $text =~ /\\w+/g );\n\nThen you've just supplied an automatic \"scalar\" in front of their argument, which can be more\nthan a bit surprising.  The old @foo which used to hold one thing doesn't get passed in.\nInstead, \"func()\" now gets passed in a 1; that is, the number of elements in @foo.  And the\n\"m//g\" gets called in scalar context so instead of a list of words it returns a boolean\nresult and advances \"pos($text)\".  Ouch!\n\nIf a sub has both a PROTO and a BLOCK, the prototype is not applied until after the BLOCK is\ncompletely defined.  This means that a recursive function with a prototype has to be\npredeclared for the prototype to take effect, like so:\n\nsub foo($$);\nsub foo($$) {\nfoo 1, 2;\n}\n\nThis is all very powerful, of course, and should be used only in moderation to make the world\na better place.\n"
                },
                {
                    "name": "Constant Functions",
                    "content": "Functions with a prototype of \"()\" are potential candidates for inlining.  If the result\nafter optimization and constant folding is either a constant or a lexically-scoped scalar\nwhich has no other references, then it will be used in place of function calls made without\n\"&\".  Calls made using \"&\" are never inlined.  (See constant for an easy way to declare most\nconstants.)\n\nThe following functions would all be inlined:\n\nsub pi ()           { 3.14159 }             # Not exact, but close.\nsub PI ()           { 4 * atan2 1, 1 }      # As good as it gets,\n# and it's inlined, too!\nsub STDEV ()       { 0 }\nsub STINO ()       { 1 }\n\nsub FLAGFOO ()     { 1 << 8 }\nsub FLAGBAR ()     { 1 << 9 }\nsub FLAGMASK ()    { FLAGFOO | FLAGBAR }\n\nsub OPTBAZ ()      { not (0x1B58 & FLAGMASK) }\n\nsub N () { int(OPTBAZ) / 3 }\n\nsub FOOSET () { 1 if FLAGMASK & FLAGFOO }\nsub FOOSET2 () { if (FLAGMASK & FLAGFOO) { 1 } }\n\n(Be aware that the last example was not always inlined in Perl 5.20 and earlier, which did\nnot behave consistently with subroutines containing inner scopes.)  You can countermand\ninlining by using an explicit \"return\":\n\nsub bazval () {\nif (OPTBAZ) {\nreturn 23;\n}\nelse {\nreturn 42;\n}\n}\nsub bonkval () { return 12345 }\n\nAs alluded to earlier you can also declare inlined subs dynamically at BEGIN time if their\nbody consists of a lexically-scoped scalar which has no other references.  Only the first\nexample here will be inlined:\n\nBEGIN {\nmy $var = 1;\nno strict 'refs';\n*INLINED = sub () { $var };\n}\n\nBEGIN {\nmy $var = 1;\nmy $ref = \\$var;\nno strict 'refs';\n*NOTINLINED = sub () { $var };\n}\n\nA not so obvious caveat with this (see [RT #79908]) is that the variable will be immediately\ninlined, and will stop behaving like a normal lexical variable, e.g. this will print 79907,\nnot 79908:\n\nBEGIN {\nmy $x = 79907;\n*RT79908 = sub () { $x };\n$x++;\n}\nprint RT79908(); # prints 79907\n\nAs of Perl 5.22, this buggy behavior, while preserved for backward compatibility, is detected\nand emits a deprecation warning.  If you want the subroutine to be inlined (with no warning),\nmake sure the variable is not used in a context where it could be modified aside from where\nit is declared.\n\n# Fine, no warning\nBEGIN {\nmy $x = 54321;\n*INLINED = sub () { $x };\n}\n# Warns.  Future Perl versions will stop inlining it.\nBEGIN {\nmy $x;\n$x = 54321;\n*ALSOINLINED = sub () { $x };\n}\n\nPerl 5.22 also introduces the experimental \"const\" attribute as an alternative.  (Disable the\n\"experimental::constattr\" warnings if you want to use it.)  When applied to an anonymous\nsubroutine, it forces the sub to be called when the \"sub\" expression is evaluated.  The\nreturn value is captured and turned into a constant subroutine:\n\nmy $x = 54321;\n*INLINED = sub : const { $x };\n$x++;\n\nThe return value of \"INLINED\" in this example will always be 54321, regardless of later\nmodifications to $x.  You can also put any arbitrary code inside the sub, at it will be\nexecuted immediately and its return value captured the same way.\n\nIf you really want a subroutine with a \"()\" prototype that returns a lexical variable you can\neasily force it to not be inlined by adding an explicit \"return\":\n\nBEGIN {\nmy $x = 79907;\n*RT79908 = sub () { return $x };\n$x++;\n}\nprint RT79908(); # prints 79908\n\nThe easiest way to tell if a subroutine was inlined is by using B::Deparse.  Consider this\nexample of two subroutines returning 1, one with a \"()\" prototype causing it to be inlined,\nand one without (with deparse output truncated for clarity):\n\n$ perl -MO=Deparse -le 'sub ONE { 1 } if (ONE) { print ONE if ONE }'\nsub ONE {\n1;\n}\nif (ONE ) {\nprint ONE() if ONE ;\n}\n$ perl -MO=Deparse -le 'sub ONE () { 1 } if (ONE) { print ONE if ONE }'\nsub ONE () { 1 }\ndo {\nprint 1\n};\n\nIf you redefine a subroutine that was eligible for inlining, you'll get a warning by default.\nYou can use this warning to tell whether or not a particular subroutine is considered\ninlinable, since it's different than the warning for overriding non-inlined subroutines:\n\n$ perl -e 'sub one () {1} sub one () {2}'\nConstant subroutine one redefined at -e line 1.\n$ perl -we 'sub one {1} sub one {2}'\nSubroutine one redefined at -e line 1.\n\nThe warning is considered severe enough not to be affected by the -w switch (or its absence)\nbecause previously compiled invocations of the function will still be using the old value of\nthe function.  If you need to be able to redefine the subroutine, you need to ensure that it\nisn't inlined, either by dropping the \"()\" prototype (which changes calling semantics, so\nbeware) or by thwarting the inlining mechanism in some other way, e.g. by adding an explicit\n\"return\", as mentioned above:\n\nsub notinlined () { return 23 }\n"
                },
                {
                    "name": "Overriding Built-in Functions",
                    "content": "Many built-in functions may be overridden, though this should be tried only occasionally and\nfor good reason.  Typically this might be done by a package attempting to emulate missing\nbuilt-in functionality on a non-Unix system.\n\nOverriding may be done only by importing the name from a module at compile time--ordinary\npredeclaration isn't good enough.  However, the \"use subs\" pragma lets you, in effect,\npredeclare subs via the import syntax, and these names may then override built-in ones:\n\nuse subs 'chdir', 'chroot', 'chmod', 'chown';\nchdir $somewhere;\nsub chdir { ... }\n\nTo unambiguously refer to the built-in form, precede the built-in name with the special\npackage qualifier \"CORE::\".  For example, saying \"CORE::open()\" always refers to the built-in\n\"open()\", even if the current package has imported some other subroutine called \"&open()\"\nfrom elsewhere.  Even though it looks like a regular function call, it isn't: the CORE::\nprefix in that case is part of Perl's syntax, and works for any keyword, regardless of what\nis in the CORE package.  Taking a reference to it, that is, \"\\&CORE::open\", only works for\nsome keywords.  See CORE.\n\nLibrary modules should not in general export built-in names like \"open\" or \"chdir\" as part of\ntheir default @EXPORT list, because these may sneak into someone else's namespace and change\nthe semantics unexpectedly.  Instead, if the module adds that name to @EXPORTOK, then it's\npossible for a user to import the name explicitly, but not implicitly.  That is, they could\nsay\n\nuse Module 'open';\n\nand it would import the \"open\" override.  But if they said\n\nuse Module;\n\nthey would get the default imports without overrides.\n\nThe foregoing mechanism for overriding built-in is restricted, quite deliberately, to the\npackage that requests the import.  There is a second method that is sometimes applicable when\nyou wish to override a built-in everywhere, without regard to namespace boundaries.  This is\nachieved by importing a sub into the special namespace \"CORE::GLOBAL::\".  Here is an example\nthat quite brazenly replaces the \"glob\" operator with something that understands regular\nexpressions.\n\npackage REGlob;\nrequire Exporter;\n@ISA = 'Exporter';\n@EXPORTOK = 'glob';\n\nsub import {\nmy $pkg = shift;\nreturn unless @;\nmy $sym = shift;\nmy $where = ($sym =~ s/^GLOBAL// ? 'CORE::GLOBAL' : caller(0));\n$pkg->export($where, $sym, @);\n}\n\nsub glob {\nmy $pat = shift;\nmy @got;\nif (opendir my $d, '.') {\n@got = grep /$pat/, readdir $d;\nclosedir $d;\n}\nreturn @got;\n}\n1;\n\nAnd here's how it could be (ab)used:\n\n#use REGlob 'GLOBALglob';      # override glob() in ALL namespaces\npackage Foo;\nuse REGlob 'glob';              # override glob() in Foo:: only\nprint for <^[a-z]+\\.pm\\$>;     # show all pragmatic modules\n\nThe initial comment shows a contrived, even dangerous example.  By overriding \"glob\"\nglobally, you would be forcing the new (and subversive) behavior for the \"glob\" operator for\nevery namespace, without the complete cognizance or cooperation of the modules that own those\nnamespaces.  Naturally, this should be done with extreme caution--if it must be done at all.\n\nThe \"REGlob\" example above does not implement all the support needed to cleanly override\nperl's \"glob\" operator.  The built-in \"glob\" has different behaviors depending on whether it\nappears in a scalar or list context, but our \"REGlob\" doesn't.  Indeed, many perl built-in\nhave such context sensitive behaviors, and these must be adequately supported by a properly\nwritten override.  For a fully functional example of overriding \"glob\", study the\nimplementation of \"File::DosGlob\" in the standard library.\n\nWhen you override a built-in, your replacement should be consistent (if possible) with the\nbuilt-in native syntax.  You can achieve this by using a suitable prototype.  To get the\nprototype of an overridable built-in, use the \"prototype\" function with an argument of\n\"CORE::builtinname\" (see \"prototype\" in perlfunc).\n\nNote however that some built-ins can't have their syntax expressed by a prototype (such as\n\"system\" or \"chomp\").  If you override them you won't be able to fully mimic their original\nsyntax.\n\nThe built-ins \"do\", \"require\" and \"glob\" can also be overridden, but due to special magic,\ntheir original syntax is preserved, and you don't have to define a prototype for their\nreplacements.  (You can't override the \"do BLOCK\" syntax, though).\n\n\"require\" has special additional dark magic: if you invoke your \"require\" replacement as\n\"require Foo::Bar\", it will actually receive the argument \"Foo/Bar.pm\" in @.  See \"require\"\nin perlfunc.\n\nAnd, as you'll have noticed from the previous example, if you override \"glob\", the \"<*>\" glob\noperator is overridden as well.\n\nIn a similar fashion, overriding the \"readline\" function also overrides the equivalent I/O\noperator \"<FILEHANDLE>\".  Also, overriding \"readpipe\" also overrides the operators \"``\" and\n\"qx//\".\n\nFinally, some built-ins (e.g. \"exists\" or \"grep\") can't be overridden.\n"
                },
                {
                    "name": "Autoloading",
                    "content": "If you call a subroutine that is undefined, you would ordinarily get an immediate, fatal\nerror complaining that the subroutine doesn't exist.  (Likewise for subroutines being used as\nmethods, when the method doesn't exist in any base class of the class's package.)  However,\nif an \"AUTOLOAD\" subroutine is defined in the package or packages used to locate the original\nsubroutine, then that \"AUTOLOAD\" subroutine is called with the arguments that would have been\npassed to the original subroutine.  The fully qualified name of the original subroutine\nmagically appears in the global $AUTOLOAD variable of the same package as the \"AUTOLOAD\"\nroutine.  The name is not passed as an ordinary argument because, er, well, just because,\nthat's why.  (As an exception, a method call to a nonexistent \"import\" or \"unimport\" method\nis just skipped instead.  Also, if the AUTOLOAD subroutine is an XSUB, there are other ways\nto retrieve the subroutine name.  See \"Autoloading with XSUBs\" in perlguts for details.)\n\nMany \"AUTOLOAD\" routines load in a definition for the requested subroutine using eval(), then\nexecute that subroutine using a special form of goto() that erases the stack frame of the\n\"AUTOLOAD\" routine without a trace.  (See the source to the standard module documented in\nAutoLoader, for example.)  But an \"AUTOLOAD\" routine can also just emulate the routine and\nnever define it.   For example, let's pretend that a function that wasn't defined should just\ninvoke \"system\" with those arguments.  All you'd do is:\n\nsub AUTOLOAD {\nour $AUTOLOAD;              # keep 'use strict' happy\nmy $program = $AUTOLOAD;\n$program =~ s/.*:://;\nsystem($program, @);\n}\ndate();\nwho();\nls('-l');\n\nIn fact, if you predeclare functions you want to call that way, you don't even need\nparentheses:\n\nuse subs qw(date who ls);\ndate;\nwho;\nls '-l';\n\nA more complete example of this is the Shell module on CPAN, which can treat undefined\nsubroutine calls as calls to external programs.\n\nMechanisms are available to help modules writers split their modules into autoloadable files.\nSee the standard AutoLoader module described in AutoLoader and in AutoSplit, the standard\nSelfLoader modules in SelfLoader, and the document on adding C functions to Perl code in\nperlxs.\n"
                },
                {
                    "name": "Subroutine Attributes",
                    "content": "A subroutine declaration or definition may have a list of attributes associated with it.  If\nsuch an attribute list is present, it is broken up at space or colon boundaries and treated\nas though a \"use attributes\" had been seen.  See attributes for details about what attributes\nare currently supported.  Unlike the limitation with the obsolescent \"use attrs\", the \"sub :\nATTRLIST\" syntax works to associate the attributes with a pre-declaration, and not just with\na subroutine definition.\n\nThe attributes must be valid as simple identifier names (without any punctuation other than\nthe '' character).  They may have a parameter list appended, which is only checked for\nwhether its parentheses ('(',')') nest properly.\n\nExamples of valid syntax (even though the attributes are unknown):\n\nsub fnord (&\\%) : switch(10,foo(7,3))  :  expensive;\nsub plugh () : Ugly('\\(\") :Bad;\nsub xyzzy : 5x5 { ... }\n\nExamples of invalid syntax:\n\nsub fnord : switch(10,foo(); # ()-string not balanced\nsub snoid : Ugly('(');        # ()-string not balanced\nsub xyzzy : 5x5;              # \"5x5\" not a valid identifier\nsub plugh : Y2::north;        # \"Y2::north\" not a simple identifier\nsub snurt : foo + bar;        # \"+\" not a colon or space\n\nThe attribute list is passed as a list of constant strings to the code which associates them\nwith the subroutine.  In particular, the second example of valid syntax above currently looks\nlike this in terms of how it's parsed and invoked:\n\nuse attributes PACKAGE, \\&plugh, q[Ugly('\\(\")], 'Bad';\n\nFor further details on attribute lists and their manipulation, see attributes and\nAttribute::Handlers.\n"
                }
            ]
        },
        "SEE ALSO": {
            "content": "See \"Function Templates\" in perlref for more about references and closures.  See perlxs if\nyou'd like to learn about calling C subroutines from Perl.  See perlembed if you'd like to\nlearn about calling Perl subroutines from C.  See perlmod to learn about bundling up your\nfunctions in separate files.  See perlmodlib to learn what library modules come standard on\nyour system.  See perlootut to learn how to make object method calls.\n\n\n\nperl v5.34.0                                 2025-07-25                                   PERLSUB(1)",
            "subsections": []
        }
    },
    "summary": "perlsub - Perl subroutines",
    "flags": [],
    "examples": [],
    "see_also": []
}