This seems reasonably natural, butpackage Before; use overload '&{}' => sub { my ( $f ) = @_; return sub { print "Stuff before\n"; goto &$f; }; };
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.)( bless sub {} => 'Before' )->()
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.
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |