in reply to One line accessor method style.

I do it all the time. No big deal. Of course, this being perl, there are a few more ways to do it...

# implicit return. sub to_xml { shift->to_html(@_) } # get rid of shifting - only if there is no one deriving off # this object, and to_html is in the same package. sub to_xml { to_html(@_) } # what are we passing in @_ for? sub to_xml { &to_html } # ah, heck, this whole thing is just an alias anyway. *to_xml = \&to_html;

Note how once we get rid of the shift, anyone who overrides to_html won't see their overridden version when the call is to_xml. So the behaviour is a little different in that case. I don't think any other use of to_xml would be different between all these ways.

Update: If the overriding difference doesn't bother you, I do think the last one is the fastest as it avoids an extra subroutine call. It's also something that many people don't see too often, so you may avoid it for that reason, too.

Replies are listed 'Best First'.
Re^2: One line accessor method style.
by Anonymous Monk on Feb 23, 2005 at 22:52 UTC

    Thanks.

    What I was really more curious about is how idiomatic the construct is. I think it's perfect for simple delegation, like this:

    sub find_text { return shift->text_control->search_for(@_) }

    where you have one object containing another and you wish to delegate certain responsibilities to the contained object.

      Idiomatic? I think pretty much all of the above are idiomatic to some degree. However, the simple case in the OP is idiomatic to any API, whether Perl, C, Java, or other. The concept is simple: we're renaming a function, but we don't want to break old code, so we'll provide a forwarding function which will call the new function automatically. In Java, this is often combined with some Javadoc that says it's @deprecated - code that is already compiled against the deprecated function will continue to work, new code trying to be compiled against it will get a warning during compilation.

      The exact syntax to get this behaviour is quite idiomatic to Perl, but what it's trying to do is common across many languages.

      As to your new example, that, too, is idiomatic to OO languages. The precise syntax, of course, is again Perlish. But the concept (the idiom) is common to OO languages everywhere - one object "HASA" second object. When I myfoot->press( mycar->get_accelerator() ) ... then a series of actions happen:

      sub Foot::press { shift; shift->press(@_); } sub Accelerator::press { my $self = shift; my $fuel_amount = $self->convert_pressure_to_liters(@_); $self->get_car()->get_engineblock()->burn_more_fuel($fuel_amount); }
      This may be written in perlish pseudo-code, but it applies the same to any other language.