Perl (Scripting) - Getting Started with Packages

by
Jeremy Canfield |
Updated: July 22 2022
| 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