in reply to %hash (@array && use constant) in Modules

Nobody seems to have touched on inheritability yet, which is more than a little important to my way of thinking. Admittedly, we're already on dangerous ground in Perl because descendent classes need to be aware of the basic representation of the data (unless they're not going to be adding any instance variables of their own and can just use the parent accessor methods).

However, arrays are much harder to subclass. For a start, when you make a subclass you have to know what the 'last' number used by the parent class was.

package FooChild; use base 'Foo'; use constant SO_FIFTH => 5; sub getFifth { my $self = shift; $self->[SO_FIFTH]; }
Which wouldn't be a problem, but what happens when you discover that you need to add an instance variable in the parent class. How do you pick a new number? You can just use the next number in the sequence, but then you have to go and modify every single child class to take this into account. Or you can pick a number that no child class has used, but then you have to remember that this number is off limits to the child class. And it all gets horrible, dependencies proliferate like bunnies and you end up with code that you don't dare change for fear of breaking something else way over there. Which is one of the problems that OO is supposed to fix.

With a hash, the workaround is relatively simple. Just pick a unique name for your hash key. Most of the time you can get away with just being careful. But if you're being paranoid you might want to always choose keys of the form 'Package::key', or use a multidimensional hash with accessors of the form

sub getFoo { my $self = shift; $self->{__PACKAGE__}{Foo} }
(If you do end up doing that it's generally a good idea to write a tool for rolling accessor methods)

Replies are listed 'Best First'.
Re: Re: %hash (@array && use constant) in Modules
by pdcawley (Hermit) on Apr 24, 2002 at 12:22 UTC
    Don't you just hate it when you realise, after hitting submit that you weren't logged on?