What follows are examples of "Hello, World" implemented in different styles of modules. It must be understood that a module is not necessary in Perl; functions and code can be defined and used anywhere. This is just for example purposes. Contrast with Java where a class is always necessary. A real "Hello, World" function would be written like so:
or simply printed in one line:
Here is "Hello, World" implemented as a procedural module with a customizable target for the greeting, just to make things interesting. Also included is a short script to illustrate the module's use.
Since Hello/World.pm is not in your @INC path, you must specify . on the command line to run the above example:
perl -I. hello_world.pl
Here's an example of the same thing done in an object-oriented style. The advantage of an OO module is that each object can be configured independently from other objects.
A running Perl program has a built-in namespace called "main", which is the default name. For example, a subroutine called Sub1 can be called as Sub1() or main::Sub1(). With a variable the appropriate sigil is placed in front of the namespace; so a scalar variable called $var1 can also be referred to as $main::var1, or even $::var1. Other namespaces can be created at any time.
Package declarations apply package scope till the next package declaration or the end of the block in which the declaration is made.
Conventionally, namespaces are associated with modules; in practice, there is usually one namespace per module and vice versa, but that's not mandated by the language. For example, the 'standard' module CGI.pm has the following declaration at its top:
This module, and its functionality, would commonly be invoked as follows:
A 'missing' subroutine could be added from the using program's namespace.
and invoked as below:
However, though technically feasible, that would be dubious programming practice. You might just as well define the sub in the calling namespace, and call it from that namespace.