It's easy to do if you know the classname at compile time. It's possible, but slightly more difficult if you don't know until runtime.
#!/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 direct approach just needs a good reference.
my $do_it = \&Foo::do_it; $do_it->('direct call');
The other way requires a bit of magic to get the proper class name and build something roughly equivalent to the last approach.

I like using eval for this sort of thing. Your mileage may vary, and you can go far with a typeglob.

my $ref = ref($foo); my $do_it2; eval "\$do_it2 = \\&${ref}::do_it"; $do_it2->('indirect call');
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').

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.


In reply to Re: function ref by chromatic
in thread function ref by jettero

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.