Scoping Issues
Subroutines may be called recursively because each call gets its own
argument array, even when the routine calls itself. If a subroutine
is called using the & form,
the argument list is optional. If the & is used but the argument list is
omitted, something special happens: the @_ array of the calling routine is
supplied implicitly. This is an efficiency mechanism that new users
may wish to avoid.
&foo(1,2,3); # pass three arguments foo(1,2,3); # the same foo(); # pass a null list &foo(); # the same &foo; # foo() gets current args, like foo(@_), but faster! foo; # like foo() if sub foo predeclared, else bareword "foo"
Not only does the &
form make the argument list optional, but it also disables any
prototype checking on the arguments you do provide. This is partly
for historical reasons and partly to provide a convenient way to
cheat if you know what you’re doing. See the section Prototypes later in this chapter.
Variables you access from inside a function that haven’t been
declared private to that function are not necessarily global
variables; they still follow the normal block-scoping rules of Perl.
As explained in the “Names” section of Chapter 2,
this means they look first in the surrounding lexical scope (or
scopes) for resolution, then on to the single package scope. From
the viewpoint of a subroutine, then, any my or state variables from an enclosing lexical
scope are still perfectly visible.
For example, the bumpx function below has access to the file-scoped ...
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