1. Perl
  2. syntax
  3. here

package - Package declaration

A feature called namespaces in other languages is called packages in Perl (* 1). A namespace is like a real-world address. I think there are several "Tatsuya Tanaka" in Japan, but there is only one "Tatsuya Tanaka" in "3- ○-△, Shinjuku-ku, Tokyo". You can decide which Tatsuya Tanaka you are by specifying the address. The namespace is the real world address.

Package declaration

Use package to declare a package.

# Package declaration
package Package name;

Specify a bare string for the package name. You cannot pass a string enclosed in quotes or double quotes.

# Specified as a bare string
package SomeModule;

Package names can be multi-tiered. Connect individual parts with "::".

# Multi-level package name
package File::Basename;
package Class::Accessor::Fast;

You can get the package to which you currently belong with __PACKAGE__.

# The name of the package to which it currently belongs
__PACKAGE__

Default namespace main

In Perl, there is no such thing as not belonging to a package. It belongs to a package called main while no package declaration is made. If you want to return to the default namespace, specify main for the package name.

# Return to default namespace
package main;

Package variable and subroutine belong to a particular package

Package variable and subroutine always belong to a particular package. This corresponds to Mr. Tatsuya Yamada (name part) explained at the beginning.

# Package variable and subroutine belong to a package
package SomeModule;

# A variable called $VAR that belongs to the package SomeModule
our $VAR;

# Subroutine called func belonging to package SomeModule
sub func {
  ...
}

Variable names and subroutine names, including package names, are called fully qualified names. The fully qualified name is the package name and variable name (or subroutine name) concatenated with "::". You can access a variable or subroutine by using a fully qualified name, even if it belongs to another package.

# Fully qualified name
$SomeModule::VAR;
SomeModule::func ();

This is an example that calls a function with a fully qualified name.

# Call a function with a fully qualified name
use File::Basename;
File::Basename::basename('xxx/yyy.txt');

Package name and module file structure

The package name is closely related to the file structure of the module. For example, if the module name is "Foo::Bar::Baz", the corresponding file structure will be "Foo/Bar/Baz.pm". Create a directory called "Bar" in a directory called "Foo" and create a file called "Baz.pm" in it. Declare the package at the beginning of "Baz.pm".

# Baz.pm
package Foo::Bar::Baz;

With such a configuration, it is possible to search for and load modules with use or require.

As a general linguistic sense, the name package is associated with a collection of libraries and modules. But be aware that when you say a package in Perl, it just means a namespace.

Related Informatrion