http://www.perlmonks.org?node_id=690349

I've written a module currently called Sub::Prepend that I'm considering for CPAN release.

Update: Uploaded to CPAN, Sub::Prepend.

The synopsis from the POD

use Sub::Prepend 'prepend'; sub foo ($) { print "Foo executed with \@_ = (@_).\n"; } BEGIN { prepend foo => sub { # This is called before foo executes. print "Foo was called with \@_ = (@_).\n"; }; } my @bar = qw/ foo bar baz /; foo(@bar); # The prototype is preserved! __END__ Foo was called with @_ = (3). Foo executed with @_ = (3).

Description / Motivation

Occasionally I want to prepend some code to subroutines, for instance to aid debugging. So I've many times repeated the code
my $old = \&foo; *foo = sub { ...; goto &$old };
That's OK as long as the subroutine name is written explicitly (and foo doesn't have a prototype I'd have to remember). Otherwise I'd need something like
use Scalar::Util 'set_prototype'; my $name = ...; my $old; my $new = sub { ...; goto &$old }; { no strict 'refs'; $old = \&$name; set_prototype(\&$new, prototype $old); no warnings 'redefine'; *$name = $new; }
and now it's pretty ugly. Putting it in a subroutine makes it a lot nicer:
prepend(foo => sub { ... });
The prototype is kept, unless explicitly overridden:
prepend(foo => sub ($) { ... }); prepend(foo => sub { ... }, { prototype => '$' });
Prototype mismatch warnings are propagated. An explicit prototype of undef "removes" any previous prototype.

Other modules

Of course, this has been done before. There's at least three modules available at CPAN that does this: Hook::WrapSub, Hook::PrePostCall, and Hook::LexWrap. Their common issue is that they try to also append code to subroutines. This requires them to hack around caller as they can't use goto &NAME and Perl doesn't have an uplevel function. Unfortunately, that hack is fundamentally broken as it won't work if the subroutine is compiled before the wrapper module is loaded. Even if you don't use the append functionality provided by those modules you get an overloaded caller that may introduce subtle bugs, like when another module tries to get extra information via the DB interface, or when another module also wants to override caller. Also, none of those modules take care of prototypes, althought that would be easy to add. Some also mess with caller context noticable by users of Want, although this too could be avoided for pure prepending operations.

Appending code is fundamentally flawed, and the caller overloading in particular is what I think motivates this module. To my knowledge, Sub::Prepend is fully transparent to the subroutine it wraps. Of course, it's noticable to code that references the subroutine, but that's a different story altogether.

Considerations

Thanks in advance,
lodin

Replies are listed 'Best First'.
Re: RFC: Sub::Prepend - Prepend code to named subroutines
by moritz (Cardinal) on Jun 05, 2008 at 12:36 UTC
    Currently it's only an exported subroutine called prepend. Is that a good name?

    I'm not a native English speaker, so my opinion might be a bit off, but... "prepend" sounds rather spatial to, like adding something at the begin of a string. I'd suggest precede instead, which sounds more temporal.

    Last but not least: would you like to see this on CPAN?

    Yes. And please describe the difference to the various Hook::* modules in the documentation ;-)

      Your* knowledge of English exceeds that of the average native speaker. Can't even see any accent from here.

      To the point, I would agree that 'prepend' is somewhat lacking. That implies a permanent attachment. I haven't got any ideas that I particularly like, but maybe you** could generate something out of 'pre', 'sub', 'hook', 'trap', and 'call' in some combination.

      *moritz, **lodin

      sas

        Actually, both the implication of permanent attachment and spatial rather than temporal seem to fit. The first is clear cut--it is a permanent modification, unlike some of the other modules that support unwrapping.

        The second is more of how you think about it. I think about it as a code block that's inserted at the very beginning, i.e. "as a string", so

        prepend foo => sub { # Remove the invocant. shift; }; sub foo { print shift; }
        is equivalent to
        sub foo { { # Remove the invocant. shift; } print shift; }
        That doesn't mean I'm set on prepend. Spelled-out suggestions are still welcome.

        lodin

        While I don't mind ::Prepend as it seems accurate given the problem space, perhaps ::Prefix might lessen the vocabulary curve without too much precision loss?

        --hsm

        "Never try to teach a pig to sing...it wastes your time and it annoys the pig."
Re: RFC: Sub::Prepend - Prepend code to named subroutines
by dragonchild (Archbishop) on Jun 05, 2008 at 12:27 UTC
    Does Sub::Compose fit the bill here? What about Class::MOP?

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
      Does Sub::Compose fit the bill here?

      Is Sub::Compose production ready? It sounds like a really nice idea, but it also sounds like not-so-robust way of doing things. (No offense meant here, just want to know).

      What about Class::MOP?

      That sounds like a great idea for methods, but does it work with subs? Also I don't see why a simple sub prepend should need a meta object protocol ;-)

        I've never used Sub::Compose in production, but you said that you're doing this for debugging purposes, so is that really a concern?

        As for Class::MOP, methods are subroutines. Subroutines are methods of their package. As for the MOP concern, you're doing this for debugging purposes. Does it really matter how it gets done?

        Also, I thought of another thing - this idea is also called Aspect-Oriented Programming and there's AOP on CPAN.


        My criteria for good software:
        1. Does it work?
        2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
Re: RFC: Sub::Prepend - Prepend code to named subroutines
by ambrus (Abbot) on Jun 05, 2008 at 13:59 UTC
Re: RFC: Sub::Prepend - Prepend code to named subroutines
by grinder (Bishop) on Jun 05, 2008 at 10:33 UTC
    Have I missed any existing module that renders Sub::Prepend unnecessary?

    I'm thinking of Hook::LexWrap.

    Update: ah, I didn't read the fine documentation apparently...

    • another intruder with the mooring in the heart of the Perl

      Hook::LexWrap is one of the modules I mention under "Other modules" and, for my purposes, unnecessarily overloads caller that made me waste time on unnecessary debugging. That's when I decided that the dangers of that hackery aren't just hypothetical.

      lodin

Re: RFC: Sub::Prepend - Prepend code to named subroutines
by theguvnor (Chaplain) on Jun 05, 2008 at 12:21 UTC

    I'd use it.

    This signature intentionally left blank.