I'm trying to make it easier to follow some Perl Best Practices by creating a Constants
module that exports several of the scalars used throughout the book. One in particular, $EMPTY_STRING
, I can use in just about every Perl script I write. What I'd like is to automatically export these scalars so I can use them without defining them explicitly in each script.
#!perl
package Example::Constants;
use Exporter qw( import );
use Readonly;
Readonly my $EMPTY_STRING => q{};
our @EXPORT = qw( $EMPTY_STRING );
An example usage:
#!perl
use Example::Constants;
print $EMPTY_STRING . 'foo' . $EMPTY_STRING;
Using the above code produces an error:
Global symbol "$EMPTY_STRING" requires explicit package name
If I change the Readonly
declaration to:
Readonly our $EMPTY_STRING => q{}; # 'our' instead of 'my'
The error becomes:
Attempt to reassign a readonly scalar
Is this just not possible with mod_perl?
You had 4 problems:
strict
and warnings
pragmas base
pragma (since it sets @ISA
for you)our
variables) can be exportedHere is the corrected module.
package Example::Constants;
use strict;
use warnings;
use base 'Exporter';
use Readonly;
Readonly our $EMPTY_STRING => q{};
our @EXPORT = qw( $EMPTY_STRING );
1;
Hmm, I missed the bit about attempting to assign to a readonly, it sounds like the module is getting loaded more than once. I believe mod_perl has a mechanism for loading modules separate from the scripts themselves. This loading happens only once, so you should be using it.
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