Given a package
package Callback; sub do_callback { my $coderef = shift; $coderef->(@_); } 1;
and a class
package Parent; use Callback; sub new { bless {}, shift } sub do_something { ... } sub init { my $self = shift; my $coderef = \&do_something; Callback::do_callback($coderef, $self); } 1;
and a sub-class
package Child; use base qw(Parent); sub do_something { ... } 1;
then, in a nearby piece of code..
my $child = Child->new;

how can I pass values to Callback::do_callback() so that it calls the $child's do_something() method, without Callback knowing in advance that an object is expected?

I know that the ref of do_something() in package Parent will be that of the subroutine defined in that class.. but it seems like there should be a nice OOPy way of calling the correct method from a package external to where that method is defined.

Obviously this is a trivial example; in practice Callback might have to deal with unforeseen packages. Also assume that the guts of Callback can be examined but not modified.

Even if Callback knows to expect an object, calling

$obj->$coderef()

does not do The Right Thing.

If I've made myself clear, is there any way of achieving this functionality?


In reply to Package coderefs by moot

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.