Background:
In Perl, the namespace is the primary way to isolate variables and functions between different parts of the program. With the package directive, independent areas are created, each receiving its own set of global variables and functions. This allows for the development of multi-file projects without name conflicts.
Problem:
Improper management of scope, mixing lexical and package variables, or incorrect handling of the "main" namespace often leads to issues: unexpected variables appearing, function overriding, obscure bugs in taxes and tests.
Solution:
package SomeName;.my) are visible only within the block, while global ones (our, previously use vars) are available throughout the package.AnotherPackage::some_function().Code example:
package MyApp::Utils; our $global_var = 10; sub do_something { return $global_var + 1; } package main; print MyApp::Utils::do_something(); # 11
Key features:
:: to access foreign resources.main is the default standard global namespace for scripts.What is the difference between my, our, and local in packages?
my — limited to the current lexical block only.our — declares a global package variable but makes it available as a lexical reference in the block.local — temporarily overrides the global value of a package variable during the block's existence.Can a function be called without explicitly specifying the package?
Yes, if the function is exported to the current package using the Exporter module and use, otherwise — only through the full name.
Can multiple packages be declared in one file?
Yes, but it's hard to understand — after each package, all subsequent declarations pertain to the new namespace. It's better to use separate files for each package.
In a command script, several packages were used in succession within a single file; variables got mixed up, sometimes lexical, sometimes global.
Pros:
Cons:
Each package was moved to its own separate module, functions were explicitly exported.
Pros:
Cons: