Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is difference between namespace, package and module in perl?

Tags:

perl

Namespace or package are same? I use Perl where we only have packages. I know there are other programming languages that also include modules.

What's the difference?

like image 720
user1363308 Avatar asked Jan 07 '13 05:01

user1363308


2 Answers

The package directive sets the namespace. As such, the namespace is also called the package.

Perl doesn't have a formal definition of module. There's a lot of variance, but the following holds for a huge majority of modules:

  • A file with a .pm extension.
  • The file contains a single package declaration that covers the entirety of the code. (But see below.)
  • The file is named based on the namespace named by that package.
  • The file is expected to return a true value when executed.
  • The file is expected to be executed no more than once per interpreter.

It's not uncommon to encounter .pm files with multiple packages. Whether that's a single module, multiple modules or both is up for debate.

like image 53
ikegami Avatar answered Oct 05 '22 21:10

ikegami


Namespace is a general computing term meaning a container for a distinct set of identifiers. The same identifier can appear independently in different namespaces and refer to different objects, and a fully-qualified identifier which unambiguously identifies an object consists of the namespace plus the identifier.

Perl implements namespaces using the package keyword.

A Perl module is a different thing altogether. It is a piece of Perl code that can be incorporated into any program with the use keyword. The filename should end with .pm - for Perl Module - and the code it contains should have a package statement using a package name that is equivalent to the file's name, including its path. For instance, a module written in a file called My/Useful/Module.pm should have a package statement like package My::Useful::Module.

What you may have been thinking of is a class which, again, is a general computing term, this time meaning a type of object-oriented data. Perl uses its packages as class names, and an object-oriented module will have a constructor subroutine - usually called new - that will return a reference to data that has been blessed to make it behave in an object-oriented fashion. By no means all Perl modules are object-oriented ones: some can be simple libraries of subroutines.

like image 44
Borodin Avatar answered Oct 05 '22 21:10

Borodin