Bootstrap FreeKB - Perl (Scripting) - Getting Started with Packages
Perl (Scripting) - Getting Started with Packages

Updated:   |  Perl (Scripting) articles

In Perl, a package is a collection of code. By default, if you do not declare a package, the main package is used. The built in __PACKAGE__ keyword can be used to know what package you are in. Take for example the following.

#!/usr/bin/perl
use strict;
use warnings;

print "Currently in this package: ",__PACKAGE__,"\n";

package Bar;
print "Currently in this package: ",__PACKAGE__,"\n";

 

Running this script should return the following, which shows the main package is used by default, and then the Bar package was used.

Currently in this package: main
Currently in this package: Bar

 

Taking this a step further, variables with the same name can be created in separate packages. In this example, the $foo variable is created in both the main and Bar packages. Then, the $foo variable from both packages can be used.

#!/usr/bin/perl
use strict;
use warnings;

package main;
our $foo = "hello";

package Bar;
our $foo = "world";

print "The \$foo variable in the main package contains a value of: $main::foo\n";
print "The \$foo variable in the Bar package contains a value of: $Bar::foo\n";

 

Running this script should return the following.

The $foo variable in the main package contains a value of: hello
The $foo variable in the Bar package contains a value of: world

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 1721d8 in the box below so that we can be sure you are a human.