Wrappers and closures and goto, oh my! Wrirting effective, re-usable wrappers in Perl and Raku.

By Steven Lembark

Elevator Pitch

Last year we went over inversion of control: Passing a piece of logic into boilerplate as a closure. This time we look at the opposite: Wrapping a sub so that it doesn’t know it’s wrapped. This technique is the guts of Multimethods and allows naive subroutines to behave normally inside the wrapper.

Description

Writing wrappers becomes problematic when they are visible: sub’s using croak() report unusable results, caller() reports the wrong layer. Combining closures with goto (Perl5) or become (Raku) allows This allows generic, re-usable closures to mange the environment and resources around a sub and then vanish, with the sub returning it’s expected results unmolested. The technique shown here is taken from Multimethods and provides for things like metadata-driven methods or testing.

Notes

Sounds esoteric at first, but this does make for really flexible, effective testing where sub being tested has no way to know a closure, say, hacked STDIN or CORE::open to return specific results.