in reply to Creating constants modules

I've coded a slightly simpler variant of that:
package MY::Constants; my %constants = ( FRED => 2, DINO => 4, WILMA => "bb-b-b-b-uck!", LARGE => 1e38, ); sub import { for (@_) { unless (exists $constants{$_}) { require Carp; Carp::croak("Constant $_ invalid"); } { no strict 'refs'; my $full_name = caller()."::$_"; my $value = $constants{$_}; # for closure *$full_name = sub () { $value }; } } } '0 but true';
Unfortunately, you lose the default import list and the other nice things with Exporter, but for quick stuff, it's nice to say:
use MY::Constants qw(FRED WILMA);

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: •Re: Creating constants modules
by nite_man (Deacon) on Mar 11, 2004 at 14:05 UTC

    I've been implementing the same thing - module which consists all project contstants. Your code is good but I'd like to make small addition. I guess we should shift package name from @_ because it's passed as first parameter:

    package MY::Constants; my %constants = ( FRED => 2, DINO => 4, WILMA => "bb-b-b-b-uck!", LARGE => 1e38, ); sub import { my $package = shift; for (@_) { unless (exists $constants{$_}) { require Carp; Carp::croak("Constant $_ invalid"); } { no strict 'refs'; my $full_name = caller()."::$_"; my $value = $constants{$_}; # for closure *$full_name = sub () { $value }; } } } '0 but true';

    ~ Schiller