Is there a standard way to code a module to hold global application parameters to be included in every other package? For instance: use Config;
?
A simple package that only contains our
variables? What about readonly variables?
There's already a standard Config module, so choose a different name.
Say you have MyConfig.pm
with the following contents:
package MyConfig;
our $Foo = "bar";
our %Baz = (quux => "potrzebie");
1;
Then other modules might use it as in
#! /usr/bin/perl
use warnings;
use strict;
use MyConfig;
print "Foo = $MyConfig::Foo\n";
print $MyConfig::Baz{quux}, "\n";
If you don't want to fully qualify the names, then use the standard Exporter module instead.
Add three lines to MyConfig.pm
:
package MyConfig;
require Exporter;
our @ISA = qw/ Exporter /;
our @EXPORT = qw/ $Foo %Baz /;
our $Foo = "bar";
our %Baz = (quux => "potrzebie");
1;
Now the full package name is no longer necessary:
#! /usr/bin/perl
use warnings;
use strict;
use MyConfig;
print "Foo = $Foo\n";
print $Baz{quux}, "\n";
You could add a read-only scalar to MyConfig.pm
with
our $READONLY;
*READONLY = \42;
This is documented in perlmod.
After adding it to @MyConfig::EXPORT
, you might try
$READONLY = 3;
in a different module, but you'll get
Modification of a read-only value attempted at ./program line 12.
As an alternative, you could declare in MyConfig.pm
constants using the constant module and then export those.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With