Modules need a package
statement and must end with a true value. (It currently returns a true value, but I like to use an explicit 1;
.) It's better to give them the .pm
extension.
# MyConfig.pm
package MyConfig;
use strict;
use warnings;
our %hash = (
"Quarter" => 25,
"Dime" => 10,
"Nickel" => 5,
);
1;
Now, if you left it at that, you'd need to use %MyConfig::hash
instead of %hash
. So we need to export the var from the module to the user's namespace.
# MyConfig.pm
package MyConfig;
use strict;
use warnings;
use Exporter qw( import );
our @EXPORT = qw( %hash );
our %hash = (
"Quarter" => 25,
"Dime" => 10,
"Nickel" => 5,
);
1;
So on to the script:
#!/usr/bin/perl
use strict;
use warnings;
use MyConfig;
for (sort keys %hash) {
print "$hash{$_}\n";
}
use MyConfig;
does a require (if necessary) and an import. The latter brings the variables and subs listed in @EXPORT
into the current namespace.