laziness, impatience, and hubris | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
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
Description / MotivationOccasionally I want to prepend some code to subroutines, for instance to aid debugging. So I've many times repeated the code
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 and now it's pretty ugly. Putting it in a subroutine makes it a lot nicer: The prototype is kept, unless explicitly overridden: Prototype mismatch warnings are propagated. An explicit prototype of undef "removes" any previous prototype. Other modulesOf 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, In reply to RFC: Sub::Prepend - Prepend code to named subroutines by lodin
|
|