ETOOBUSY 🚀 minimal blogging for the impatient
defer
TL;DR
In recent post [En guarde! Playing with Guard][] we took a look at Guard, and I was almost forgetting about a similar functionality that has been baked into our beloved Perl interpreter: defer.
It more or less covers of the functionality of scope_guard
, so depending
on the interpreter that you can count on it might go as a total replacement
if we don’t need anything fancier (like the possibility to change our mind
at some later-yet-intermediate stage).
Transforming our first program from the previous post is straightforward, keeping in mind that defer takes a block of code (not a code reference):
#!/usr/bin/env wrapperl
use v5.38;
use warnings;
use experimental 'defer';
$|++;
scoped(shift // 'die');
sub scoped ($what) {
defer { en_guarde() }
if ($what eq 'die') {
die "whatever!";
}
elsif ($what eq 'return') {
say 'about to return...';
return;
}
elsif ($what eq 'exit') {
say 'exiting...';
exit 1;
}
else {
say 'dumpiiiing!';
CORE::dump();
}
}
sub en_guarde { warn "en_guarde(@_)!" }
The result is the same as the Guard case:
$ ./defer-1.pl die
whatever! at ./defer-1.pl line 13.
en_guarde()! at ./defer-1.pl line 29.
$ ./defer-1.pl return
about to return...
en_guarde()! at ./defer-1.pl line 29.
$ ./defer-1.pl exit
exiting...
en_guarde()! at ./defer-1.pl line 29.
$ ./defer-1.pl dump
dumpiiiing!
Aborted
So well, I think that Guard still makes a lot of sense until pre-5.36 interpreter will be significantly around, or sophisticated guards are needed. Otherwise… you can defer its installation!