Functions and Namespaces

Learn about functions and namespaces in Perl.

Namespace of the functions

Every function has a containing namespace. Functions in an undeclared namespace (functions not declared within the scope of an explicit package statement) exist in the main namespace. We may also declare a function within another namespace by prefixing its name:

sub Extensions::Math::add { ... }

This will create the namespace as necessary and then declare its function within it. Remember that Perl packages are open for modification at any point, even while our program is running. Perl will issue a warning if we declare multiple functions with the same name in a single namespace.

Referring to functions from namespaces

Refer to other functions within the same namespace with their short names. Use a fully qualified name to invoke a function in another namespace:

package main;

Extensions::Math::add( $scalar, $vector );

Remember, functions are visible outside their own namespaces through their fully qualified names. Alternatively, we may import names from other namespaces.

Note: Perl 5.18 added an experimental feature to declare functions lexically. They’re visible only within lexical scopes after declaration. See the “Lexical Subroutines” section of perldoc perlsub for details.

Importing

When loading a moduleA module is a package contained in its own file and loadable with use or require. with the use built-in, Perl automatically calls a method named import(). Modules can provide their own import() method, which makes some or all defined symbols available to the calling package. Any arguments after the name of the module in the use statement get passed to the module’s import() method. We can load the strict.pm module and call strict->import() with no arguments with:

use strict;

Get hands-on with 1200+ tech skills courses.