I would like to create a class whose objects are blessed coderefs, with the property that attempting to de-reference an object of the class produces a ‘wrapper’ subroutine that does some work before calling the original subroutine. My naïve attempt went something like this:
package Before; use overload '&{}' => sub { my ( $f ) = @_; return sub { print "Stuff before\n"; goto &$f; }; };
This seems reasonably natural, but
( bless sub {} => 'Before' )->()
just prints Stuff before over and over—because the implicit de-referencing of $f in the use overload statement itself triggers a call to the overloaded de-referencing behaviour, and so on recursively. Is there a way to get the ‘true’ behaviour of an overloaded object? (I thought that I saw someone here mention overload::Method for precisely this purpose, but I must have misunderstood—it returns a coderef to the new, not the old, behaviour.)

I know that there are ways around this—for example, I could arrange that the constructor wraps the subroutine at construction time, rather than de-referencing time; or I could make the objects of the class references to coderefs, so that the coderef itself would not have any overloading defined—but, at the risk of asking an XY question, I'd like to do it this way! Is it possible?

UPDATE 1: There are some lovely alternate approaches below. It's interesting to see how great minds think alike; see particularly Re^5: Overloading without infinite descent and Re^3: Overloading without infinite descent, or Re^7: Overloading without infinite descent and Re: Overloading without infinite descent.
UPDATE 2: It seems that the new overloading pragma will do exactly what I want.


In reply to Overloading without infinite descent (fixed by time: see Perl 5.10.1) by JadeNB

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.