Raku (née Perl 6) has phasers that will be called when exiting a scope. One such idiom is:
{
# do stuff
my $dbh = DB.connect(...);
# do stuff
LEAVE .disconnect with $dbh;
# do stuff
}
Whenever the scope is left (this could be because of an execution error, or a `return`), the code of the LEAVE phaser will be executed. The `with $dbh` checks whether the $dbh variable contains an instantiated object. If so, it topicalizes (set $_ to it) and calls the disconnect method (`.disconnect` being short for `$_.disconnect`).For more complex uses, and more tuneable finalizing, there is the `FINALIZER` module in the ecosystem: https://modules.raku.org/dist/FINALIZER