Subroutine Scope
Just like variables, subroutine names are simply entries in a symbol table or lexical scratchpad. So, all subroutines live in a particular scope, whether it’s lexical, package, or global scope.
Package-Scoped Subroutines
Package scope is the default scope for subs.
A sub that is declared without any scope marking is accessible within
the
module or class where
it’s defined with an unqualified call, like
subname( ), and accessible elsewhere with a fully
qualified call using the Package::Name::subname( )
syntax.[13]
module My::Module {
sub firstsub ($param) { . . . }
sub secondsub {
mysub('arg'); # call the subroutine
}
}
module Other::Module {
use My::Module;
sub thirdsub {
My::Module::firstsub('arg');
}
}This example declares two modules, My::Module and
Other::Module. My::Module
declares a subroutine firstsub and calls it from
within secondsub. Other::Module
declares a subroutine thirdsub that calls
firstsub using its fully qualified name.
Lexically Scoped Subroutines
Subroutines can also be
lexically scoped, just like
variables. A myed subroutine makes an entry in the
current lexical scratchpad with a & sigil.
Lexically scoped subs are called just like a normal subroutine:
if $dining {
my sub dine ($who, $where) {
. . .
}
dine($zaphod, "Milliways");
}
# dine($arthur, "Nutri-Matic"); # errorThe first call to the lexically scoped dine is
fine, but the second would be a compile-time error because
dine doesn’t exist in the outer
scope.
The our keyword declares a lexically ...
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