Yesterday evening, after a long days work (just in my defense), I was working on some wrapper code. One of the features required for a method reference. I initially had this:
$method = $object->method;which wasn't doing anything close to what I needed. I soon realized that I didn't need the output but the actual subroutine reference.. so I came up with:
$method = \&{$object->method};At that time, it was about 1 AM (and I had spend the better part of the evening watching TV while not trying to think about code in an effort to come to an aha-erlebnis. Something like
$method = \&Object::method;might be a better idea, as long as I don't forget to pass the
$object
as the first argument.$method = sub { $object->$method };
-Dom
Re:Coderefs?
Beatnik on 2006-11-08T11:58:59
Now that I've had some coffee, I can't really remember anymore what I already got and what I was considering on using... *must.. race .. home .. quickly* Re:Coderefs?
Dom2 on 2006-11-08T13:36:49
I sympathise. I've often wondered deeply on the following day about code that got written after midnight...-Dom
$method = \&Object::method;
Hardcoding considered suboptimal (for a range of reasons). You want this:
$method = $object->can( 'method' );
You have to remember to pass a reference to $object
in either case, though. No getting around that in Perl.
Therefore you would normally use a closure as per Dominic’s suggestion.