bobf has asked for the wisdom of the Perl Monks concerning the following question:
Hello, monks. I am new to OOP and I'm in the process of creating my very first class. The structure of the objects from this class is a hash of hashes (simplified):
%object okey1 ikey1 = value ikey2 = value okey2 ikey3 = value ikey4 = value
I read the section entitled "Putting All Your Eggs in One Basket" in perltootc from ActiveState, which describes how to use closures to create methods to access class data. I tweeked the code so I could use it to create instance methods:
{ # bare block to limit the scope of %obj_structure # use closures to create accessor methods for each attribute my %obj_structure = ( okey1 => [ qw( ikey1 ikey2 ) ], okey2 => [ qw( ikey3 ikey4 ) ] ); foreach my $okey ( keys %obj_structure ) { foreach my $ikey ( @{ $obj_structure{$okey} } ) { # use symbolic refs to access the symbol table no strict 'refs'; *$var = sub { my $self = shift @_; my ( $value ) = shift @_; if( defined $value ) { $self->{$okey}{$ikey} = $value; } return $self->{$okey}{$ikey}; } } } }
This seems like it would be a great way to easily create instance methods for arbitrarily complex objects, but I wonder whether this approach is an acceptable way to create instance methods. If there is a better/safer way to do this, please enlighten me. For this case I don't need to worry about inheritance, but if there are issues with this approach with respect to inheritance, I'd appreciate knowing where the pitfalls are.
Comments and suggestions are welcome. Thanks in advance!
Update: I just found an eerily similar example of this use in AUTOLOAD - the good, the bad, and the ugly, where it was discussed in the context of AUTOLOAD. A couple of modules were mentioned (Class::MethodMaker and Class::MakeMethods) as an alternative to AUTOLOAD. I'm not sure how to use AUTOLOAD with a complex data structure (methods may have to go through HoA, HoH, HoHoA, etc, depending on $ikey), and I need to keep the number of dependencies (CPAN modules) to a minimum for the users. Is this approach acceptable? Thanks again.
Update: fixed link to perltootc, which apparently has been renamed to perltooc to fit the 8+3 filename scheme (thanks, ihb!)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Creating instance methods using closures
by borisz (Canon) on Oct 15, 2004 at 00:00 UTC | |
|
Re: Creating instance methods using closures
by BUU (Prior) on Oct 15, 2004 at 01:23 UTC | |
by TheEnigma (Pilgrim) on Oct 15, 2004 at 01:39 UTC | |
|
Re: Creating instance methods using closures
by simonm (Vicar) on Oct 15, 2004 at 15:18 UTC |