jffry has asked for the wisdom of the Perl Monks concerning the following question:

I have a list of constants that will be common to a lot of modules and Perl scripts. I've looked around, and this is what I have come up with. It works, but is it best-practicy enough?

File tt.pl:
use warnings; use strict; use ddd; print "APPLE = $apple \n"; exit 0;
File ddd.pm:
use strict; use warnings; package ddd; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw( $apple $pear ); use Readonly; Readonly our $apple => "funny"; Readonly our $pear => "bad"; 1;
Any thoughts?

Replies are listed 'Best First'.
Re: Export Constants Common to Lots of Packages
by ikegami (Patriarch) on Nov 29, 2005 at 19:00 UTC
    If you wished to use true constants,
    use strict; use warnings; package ddd; require Exporter; our @ISA = qw( Exporter ); our @EXPORT = qw( APPLE PEAR ); use constant APPLE => "funny"; use constant PEAR => "bad"; 1;
    use strict; use warnings; use ddd; print "APPLE = " . APPLE . "\n";

        Same here. At work, we've recently removed "use constant" from our code and converted to Readonly due to Damian's advice. It's really cleaned up a lot of our code.

        Unfortunately, there are some bugs in how Perl handle tie which Readonly exposes. For example, the following prints "no":

        #!/usr/bin/perl -l use strict; use warnings; use Readonly; Readonly my $VAR => 'SEARCH'; foreach my $var ($VAR) { print +($var eq $VAR) ? 'yes' : 'no'; }

        Clearly that's wrong, but it's related to Perl's tie mechanism and not Readonly. As a workaround:

         print +($var.'' eq $VAR.'') ? 'yes' : 'no';

        That's ugly as sin, but it works :(

        Cheers,
        Ovid

        New address of my CGI Course.

        Constants are different than normal variables, so I like how use constant constants look differently (due to lack of a sigil). Isn't that one of Perl's mantras?

        Readonly uses tie. Tied variables are slower, and they behave erratically in a few situations.

        On the other hand, Readonly works on types other than scalar.