In a class I'm coding, I have a method that
calls a code ref to process an argument,
another to initialize that code ref,
and two (e.g.) other methods that
handle the processing.
Stripped down, the example looks like this:
sub foo_a {
my ($self, $arg) = @_;
# method A for processing $arg
}
sub foo_b {
my ($self, $arg) = @_;
# method B for processing $arg
}
sub foo {
my ($self, $arg) = @_;
$self->{'foo_code'}->($self, $arg); # XXX
}
sub foo_set {
my ($self, $code) = @_;
$self->{'foo_code'} = $code;
}
The user has access to the specific foo_a() and foo_b()
methods, or can use foo() to call whatever's
registered as the current underlying method.
The line marked "XXX" above bugs me.
Having to simulate an object-call to the underlying method
by explicitly repeating $self in the calling sequence feels ugly.
Is there a better way that this can be done more "directly?"
I had some success
changing foo_set() to fiddle with typeglobs
as a way of "aliasing" foo() to the underlying method,
but this gets in the way of letting users
supply their own processing functions
via an anonymous code ref:
$obj->foo_set(sub { # process $_[1] });
Is there any magic I'm overlooking that cleans this up?
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.