Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I export Readonly variables with mod_perl?

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?

like image 978
cowgod Avatar asked Jan 23 '23 17:01

cowgod


1 Answers

You had 4 problems:

  1. You weren't including the strict and warnings pragmas
  2. It is better to include exporter through the base pragma (since it sets @ISA for you)
  3. Only package variables (i.e. our variables) can be exported
  4. Modules must end with a true value

Here 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.

like image 174
Chas. Owens Avatar answered Jan 26 '23 07:01

Chas. Owens