Why are you using symbolic references?I have learnt a lot on manipulating references in objects from tilly's1 and Schemer's2 thoughtful nodes. tillys's node talks about functional programming techniques in Perl. It seems to me that it would be a good idea to actually store the references to functions in the hash, not just their names. They're the ones you're working with, after all, so why force perl to take the extra step?
Anyhow, based on these nodes, I came up with the following:
package DynamicObject; sub new { my ( $pkg, %args ) = @_; my $self = { "method" => \&correlation, %args }; return bless $self, $pkg; } sub correlation { print "This is the correlation function!\n"; } sub setMethod { my ( $self, $key, $function ) = @_; $self -> { $key } = $function; } sub callMethod { my ( $self, $function, @arguments ) = @_; if( exists $self -> { $function } ) { &{ $self -> { $function } }( @arguments ); } else { print "Unknown function '$function' called.\n"; } } 1;
It is used like so:
use DynamicObject; my $object = DynamicObject -> new (); $object -> callMethod( "method" ); $object -> setMethod( "method", \&another ); $object -> callMethod( "method" ); $object -> callMethod( "fnap" ); $object -> setMethod( "fnap", \&ya ); $object -> callMethod( "fnap", qw{ Hey ho! We wont go!} ); sub another { print "This is another function!\n"; } sub ya { print "This is yet another function called with ". "arguments '", join( " ", @_ ), "'!\n"; }
Which outputs:
This is the correlation function! This is another function! Unknown function 'fnap' called. This is yet another function called with arguments 'Hey ho! We wont go +!'!
callMethod() has a simple error-check to see whether the object actually has the method. Any arguments passed to callMethod() is forwarded to the the method in question, if it exists.
I really, really recommend the two above mentioned nodes to anyone playing around with references in Perl. Hope this helps.
Update: After a reread, I realize that my tone in this post was a bit arrogant. I have rewritten parts of the message to reflect my respect of both the problem at hand and the nodes i refer to. I offer my apologies to those I have offended.
pernodIn reply to Re: reference to self function
by pernod
in thread reference to self function
by anjiro
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |