Changing the Package
The notion of “current package” is both a compile-time and
runtime concept. Most variable name lookups happen at compile time,
but runtime lookups happen when symbolic references are dereferenced,
and also when new bits of code are parsed under eval. In particular, when you eval a string, Perl knows which package the
eval was invoked in and propagates
that package inward when evaluating the string. (You can always switch
to a different package inside the eval string, of course, since an eval string counts as a block, just like a
file loaded in with do, require, or use.)
For this reason, every package declaration must declare a complete package name. No package name
ever assumes any kind of implied “prefix”, even if (seemingly) it is
declared within the scope of some other package declaration.
Alternatively, if an eval
wants to find out what package it’s in, the special symbol _ _PACKAGE_ _ contains the current package name. Since you can treat
it as a string, you could use it in a symbolic reference to access a
package variable. But if you were doing that, chances are you should
have declared the variable with our
instead so it could be accessed as if it were a lexical.
Any variable not declared with my (or state) is associated with a package—even
seemingly omnipresent variables like $_ and %SIG. Other variables use the current
package, unless they are qualified:
$name = 'Amelia'; # name in current package $Animal::name = 'Camelia'; # name in Animal package
The ...
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