DOKK / manpages / debian 12 / libaspect-perl / Aspect::Advice::Before.3pm.en
Aspect::Advice::Before(3pm) User Contributed Perl Documentation Aspect::Advice::Before(3pm)

Aspect::Advice::Before - 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 "before" 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 "before" 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 "highest" pointcut (Aspect::Pointcut::Highest) is incompatible with "before". Creating a "before" advice with a pointcut tree that contains a "highest" pointcut will result in an exception.

If speed is important to your program then "before" is particular interesting as the "before" implementation is the only one that can take advantage of tail calls via Perl's "goto" function, where the rest of the advice types need the more costly Sub::Uplevel to keep caller() returning correctly.

Adam Kennedy <adamk@cpan.org>

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.

2022-06-08 perl v5.34.0