Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Constants and Subclasses...

by t'mo (Pilgrim)
on Dec 18, 2006 at 22:38 UTC ( #590571=note: print w/replies, xml ) Need Help??

in reply to Constants and Subclasses...

Thanks for the suggestions. My code is evolving somewhat differently than the suggested code (mostly to avoid the duplication implicit in both use const NAME and putting NAME in @EXPORT). I agree that it's unfortunate that the namespace is polluted via all the Exporter stuff, but hey, it works. (Note: ParentClass is defined in another file, I just didn't mention it before.)

package ParentClass; BEGIN { my %constants = ( FOO => 'foo', BAR => 'bar', BAZ => 'baz', ); foreach my $name ( keys %constants ) { no strict 'refs'; *{$name} = sub () { $constants{$name} }; } our @EXPORT = keys %constants; } # -------- new file -------- package ChildClass; use base 'ParentClass'; BEGIN { ParentClass->import(); } sub doStuff { my ($self, @otherArguments) = @_; print FOO; # Yay, it works this time! ... }

Edit: changed scalar constants to hash.

Replies are listed 'Best First'.
Re^2: Constants and Subclasses...
by diotalevi (Canon) on Dec 19, 2006 at 22:18 UTC

    You wrote:
    BEGIN { my $constants = ( FOO => 'foo', BAR => 'bar', BAZ => 'baz', ); foreach my $name ( keys %constants ) { no strict 'refs'; *{$name} = sub () { $constants{$name} }; } ... }</blockquote>
    If you're going to make constants, do them the proper way with the constant pragma. What you wrote is roughly how works in versions prior to 5.9 but the next versions of perl have a different implementation for constant and you'll want your code to do the right thing regardless.

    BEGIN { require constant; my %constants = ( FOO => 'foo', BAR => 'bar', BAZ => 'baz', ); foreach my $name ( keys %constants ) { constant->import( $name => $constants{$name} ); } }

    You also goofed and made a variable $constants instead of %constants.

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

        Well sure. use constant FOO => 'bar'; is just shorthand for the following:

        BEGIN { require constant; constant->import( FOO => 'bar' ); }

        ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://590571]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2017-08-21 06:45 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (317 votes). Check out past polls.