Execute code both before and after a function
use Aspect; around { # Trace all calls to your module print STDERR "Called my function " . $_->sub_name . "\n"; # Lexically alter a global for this function local $MyModule::MAXSIZE = 1000; # Continue and execute the function $_->run_original; # Suppress exceptions for the call $_->return_value(1) if $_->exception; } call qr/^ MyModule::\w+ $/;
The \*(C`around\*(C' advice type is used to execute code on either side of a function, allowing deep and precise control of how the function will be called when none of the other advice types are good enough.
Using \*(C`around\*(C' advice is also critical if you want to lexically alter the environment in which the call will be made (as in the example above where a global variable is temporarily changed).
This advice type is also the most computationally expensive to run, so if your problem can be solved with the use of a different advice type, particularly \*(C`before\*(C', you should use that instead.
Please note that unlike the other advice types, your code in \*(C`around\*(C' is required to trigger the execution of the target function yourself with the \*(C`proceed\*(C' method. If you do not \*(C`proceed\*(C' and also do not set either a \*(C`return_value\*(C' or \*(C`exception\*(C', the function call will return \*(C`undef\*(C' in scalar context or the null list \*(C`()\*(C' in list context.
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.