in reply to Named array indices

package Your::Class; our $VERSION= 1.001_001; package Your::Class::_Implementation; BEGIN { require constant; my $offset= 0; for my $member ( qw< _NAME _ADDRESS _PHONE ... > ) { constant->import( $member, $offset++ ); } } sub Your::Class::new { ... $self->[_NAME]= ...; }

If you don't like writing "sub Your::Class::new" instead of "sub new", then you can instead do something like:

... package Your::CLass::_Implementation; ... sub new { ... } ... package Your::Class; BEGIN { require Exporter; for my $method ( qw< new ... > ) { Exporter::import( 'Your::Class:_Implementation', $method ); } }

This also allows you to separate your class methods fom your ojects methods, just FYI.

It isn't difficult to abstract out these tools to make them look prettier.

Note that a C' prefix is a horrible idea:

package Your::Class; ... sub C'Name() { 0; } ... package Something::Completely::Different; ... sub C'Index() { 0; } sub C'Name() { 1; } # Boom! ...

- tye        

Replies are listed 'Best First'.
Re^2: Named array indices (packages)
by choroba (Cardinal) on Aug 06, 2010 at 09:02 UTC
    Note that a C' prefix is a horrible idea:
    You probably missed (as did I) the second paragraph in perlmod:
    The old package delimiter was a single quote, but double colon is now the preferred delimiter...

      Uh, no. A C:: prefix is equivalently horrible (of course). That was the point. Perhaps you missed the "Boom!" comment? Or did you not understand the significance of it?

      - tye        

        Oh, the latter.
Re^2: Named array indices (packages)
by LanX (Saint) on Aug 06, 2010 at 12:59 UTC
    Note that a C' prefix is a horrible idea:

    Well the problem is the same for double colon syntax.

    I would need relative package paths but can't achieve them easily.

    I couldn't even make something like $arr[__PACKAGE__::C::Index] or $arr[__PACKAGE__.'::C::Index'] expand correctly at compile time.

    So BUK has a point to use underscore prefixes!

    Anyway my intention to use a package for the array indices was to avoid polluting the package namespace with constants which should only be associated and encapsulated to special datastructures.

    I'm not completely understanding the code you're showing, looks like your globally importing the constants into the package and facilitating the initialization of the index-values. (As a side node there is constant::lexical2 on CPAN)

    Thanx!

    Cheers Rolf

    UPDATE: did clarification of two phrases.