laziness, impatience, and hubris | |
PerlMonks |
Re: coderef to an object methodby ambrus (Abbot) |
on Jul 21, 2004 at 09:04 UTC ( [id://376182]=note: print w/replies, xml ) | Need Help?? |
When you call methods, it would not be easy to take a code reference, as the function that gets called depends on the class that the object is blessed into. (A module might even do tricks like blessing objects to different classes depending on its constructor options or even rebless it when it changes a state; or it can change the method dynamically with AUTOLOAD or else.) Thus, the perl equivalent of a pointer to method is to simply use a string. There's a less known way to call a method inderectly via a string, which is like this:
The problem with this notation is that you can not replace the method name with an arbitary braced expression, so you must use for example if you use a more complicated expression than a single variable. (Doesn't anyone know where this indirect method syntax is documented in perldoc?) Update 2: Ah, it seems that I have misuderstood your question. If I understand correctly, you need code references so that you can give it as callbacks. I still say you should not directly take coderefs to a method, as that would break the OO approach. Instead, you need to create anonymous functions that call the method, like this:
Or you can factor the subroutine creations out like this:
Update 3: it seems that etcshadow has already given essentially the same answer.
In Section
Seekers of Perl Wisdom
|
|