perl function package

The package keyword in Perl is used to declare the current namespace or to switch to a different namespace. It is used to organize the code and variables into logical groups.

Here's an example of using the package keyword to define a new namespace:

refer to:‮igi‬ftidea.com
package MyPackage;

sub mysub {
    print "Hello, World!\n";
}

1;

In this example, we create a new namespace called MyPackage and define a subroutine called mysub within it. The 1; at the end of the file is required by Perl to indicate that the package definition was successful.

Once the package is defined, we can use its functions and variables from other parts of the code:

use MyPackage;

MyPackage::mysub();

In this example, we use the MyPackage namespace and call the mysub subroutine from it using the namespace qualifier MyPackage::.

We can also switch to a different namespace using the package keyword:

package AnotherPackage;

sub anothersub {
    print "Hello, Perl!\n";
}

1;

In this example, we define a new namespace called AnotherPackage and define a subroutine called anothersub within it. We can then switch to this namespace using the package keyword:

package main;

use AnotherPackage;

AnotherPackage::anothersub();

In this example, we switch back to the main namespace and use the AnotherPackage namespace. We can then call the anothersub subroutine from the AnotherPackage namespace using the namespace qualifier AnotherPackage::.