Aspect...Before(3pm)

πŸ“¦
version 1.04 Β· 3 versions
, in debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– Aspect::Before β€” bestie edition πŸ’–

okay so this is from the User Contributed Perl Documentation collection, it's called Aspect...Before(3pm), and it's genuinely one of the cutest little advice types out there. let's get into it 🫢


✨ NAME ✨

Aspect::Advice::Before β€” Execute code before a function is called πŸ’…


✨ SYNOPSIS ✨

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+ $/

like… the way this just works? no cap. you literally write a block and it runs before every matching sub. iconic behavior fr fr 🌸


✨ DESCRIPTION ✨

so the before advice type is the one you reach for when you want your advice code to run prior to entry into a target function β€” like, before the function even gets a chance to breathe. it's implemented by Aspect::Advice::Before, which is the whole reason this page exists πŸŽ€

and bestie, it does more than just cause side effects that run ahead of the main code. before is particularly useful for two very specific glow-ups:

  • changing parameters πŸ¦‹
  • shortcutting calls to functions entirely, and replacing the value they would normally return with a different value πŸ’«

like, you can just… swap the return value out from under it. main character energy tbh.

⚠️ IMPORTANT CAVEAT, PAY ATTENTION ⚠️ β€” the highest pointcut (Aspect::Pointcut::Highest) is incompatible with before. if you build a before advice with a pointcut tree that contains a highest pointcut, you will get an exception. it's giving "do not do this", so don't do this πŸ’€

and now for the part that makes the performance girlies feral: if speed matters to your program, before is particularly interesting because it's the only implementation that can take advantage of tail calls via Perl's goto function. every other advice type has to use the more costly Sub::Uplevel to keep caller() returning correctly. so like… before is lowkey the fast one πŸ‘‘πŸ”₯


✨ AUTHORS ✨

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. 🫢


mwah πŸ’‹ that's the whole page. go forth and run code before things, bestie.

this page shipped as part of perl v5.36.0, dated 2023-07-02 β€” so if you're reading this, tell the version and the date I said hi πŸ’œβœ¨

πŸ“¦ where this page comes from