Execute code before a function is called
use Aspect; before { # Trace all calls to your module print STDERR "Called my function " . $_->sub_name . "\n"; # Shortcut calls to foo() to always be true if ( $_->short_name eq 'foo' ) { return $_->return_value(1); } # Add an extra flag to bar() but call as normal if ( $_->short_name eq 'bar' ) { $_->args( $_->args, 'flag' ); } } call qr/^ MyModule::\w+ $/
The \*(C`before\*(C' advice type is used to execute advice code prior to entry into a target function. It is implemented by Aspect::Advice::Before.
As well as creating side effects that run before the main code, the \*(C`before\*(C' advice type is particularly useful for changing parameters or shortcutting calls to functions entirely and replacing the value they would normally return with a different value.
Please note that the \*(C`highest\*(C' pointcut (Aspect::Pointcut::Highest) is incompatible with \*(C`before\*(C'. Creating a \*(C`before\*(C' advice with a pointcut tree that contains a \*(C`highest\*(C' pointcut will result in an exception.
If speed is important to your program then \*(C`before\*(C' is particular interesting as the \*(C`before\*(C' implementation is the only one that can take advantage of tail calls via Perl's \*(C`goto\*(C' function, where the rest of the advice types need the more costly Sub::Uplevel to keep caller() returning correctly.
Adam Kennedy <[email protected]>
Copyright 2010 - 2013 Adam Kennedy.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.