The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


Sub::ScopeFinalizer - execute a code on exiting scope.


Version 0.02


 use Sub::ScopeFinalizer qw(scope_finalizer);
   my $anchor = scope_finalizer { print "put clean up code here.\n"; };
   print "running block.\n";


Sub::ScopeFinalizer invoke BLOCK, triggered by leaving a scope. It is similar to destructor or finally clause.


This module exports one function, scope_finalizer.



 $o = scope_finalizer BLOCK;
 $o = scope_finalizer BLOCK { args =>[...] };

Create a finalizer object. This is shortcut to invoke Sub::ScopeFinalizer->new(...).

BLOCK will be executed when object is destroyed. In other words, process just exits a scope which object is binded on.

Second argument is optional hashref. $opts->{args} can contain argument for BLOCK as ARRAYref.

If you only call this function without bind, BLOCK is executed immediately because object is destroyed as soon as return from function. Don't forget to bind.



$pkg->new(CODEref, HASHref);

Create a finalizer object. You must bind it with variable on scope.

See "scope_finalizer".




Invoke finalizer before it run automatically. This method disables default invokation on scope leaving.

This method takes one argument as optional hashref. $opts->{args} can contain argument for BLOCK as ARRAYref. if $opts->{args} is passed, args parameter on constructor is ignored.



Turn off BLOCK invoking. If optional argument $flag is passwd and it is false, cancel disabling, that is, enable invoking.


YAMASHINA Hio, <hio at>


Please report any bugs or feature requests to bug-sub-scopescope_finalizer at, or through the web interface at I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.


You can find documentation for this module with the perldoc command.

    perldoc Sub::ScopeFinalizer

You can also look for information at:



Copyright 2006 YAMASHINA Hio, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.