method references in perl
Hi! I am trying to create a hard reference to a method bound to an object (yes, blessed reference) with perl, while 'use strict' is on. I am not able to find the correct syntax, neither
\&$self->method nor \&{$self->method} compile. Can anybody help me? Thanks, mschutte |
You can call a method stored in a variable by just putting the variable in the place you'd normally put the name of the method. For instance:
Code:
# say you've got an $object, and a method poke_me |
Well, great stuff, but it's not what I need. Using this method, I still have to tell the blessed ref to operate on. Probably you understand what I mean if I explain what I need it for.
I am using XML::Parser in a class and want to assign the handlers to some methods. This means: my $expat = new XML::Parser(Handlers => { Start => \&startElement }); but with a method instead of a function call: my $expat = new XML::Parser(Handlers => { Start => \&$self->startElement }); when $self is a blessed reference. It doesn't work. Is there any way to make it work? If yes, please post a reply... Thanks, mschutte |
Ah, I see. Ok, well depending on whether you want to call the method as an object method or a class method, it will be different. If the method you want to call is dependent on the object's state, you want the object call, and you'd do it with a closure, like this:
Code:
my $object = Whatever->new; Code:
my $object = Whatever->new; To anyone reading this, I highly recommend learning to use closures, they can be incredibly powerful and elegant solutions. |
Yes, really elegant. Thank you!
-- mschutte |
All times are GMT -5. The time now is 10:00 PM. |