I have some code I'll be posting soon that illustrates this better, but try using the 'can' method. The advantage to this approach is it even passes 'use strict;'

sub foo_set { my ($self, $code) = @_; my $code_ref = $self->can($code); if (defined($code_ref)) { $self->{'foo_code_ref'} = $code_ref; } else { die "Unable to handle '$code'"; } } sub foo { my ($self, $arg) = _; my $code_ref = $self->{'foo_code_ref'}; $self->code_ref($arg); }

The 'can' method determines if the class can use that method and returns a code reference. You can then just call the code reference on the object. And like I said, it will pass 'use strict'. With error checking and Carp::croak, you can make it even telling you where in the calling code you made a type.

This works in at least perl 5.005_03 and I believe also in perl 5.004. I don't know about older version of perl.

This takes advantage of the 'can' method in the UNIVERSAL package which every package inherits from. If you override the 'can' function in your inheritance tree, this won't work. But that should rarely happen.


In reply to RE: cleaning up an indirect by johannz
in thread cleaning up an indirect by knight

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.