in reply to function ref
The direct approach just needs a good reference.#!/usr/bin/perl -w use strict; package Foo; sub new { bless({}, $_[0]); } sub do_it { print "Doing something for $_[0]!\n"; } package main; my $foo = new Foo;
The other way requires a bit of magic to get the proper class name and build something roughly equivalent to the last approach.my $do_it = \&Foo::do_it; $do_it->('direct call');
I like using eval for this sort of thing. Your mileage may vary, and you can go far with a typeglob.
The eval uses backslashes to make sure $do_it2 isn't interpolated and the ampersand isn't escaped. The braces around foo let the interpreter know that we only want $ref not $ref::do_it ($do_it in the package named 'ref').my $ref = ref($foo); my $do_it2; eval "\$do_it2 = \\&${ref}::do_it"; $do_it2->('indirect call');
Update: If I took the time to stop and to think about it, I would use can as the brilliant and thoughtful btrott so sagely postulates.
|
|---|