http://www.perlmonks.org?node_id=72887
Description: Call an anon sub as it is destroyed. (Typically by going out of scope.) For instance:
use strict; use Cwd; use Carp; use ReleaseAction; sub cd_to { chdir($_[0]) or confess("Cannot chdir to '$_[0]': $!"); } sub temp_cd { my $cwd = cwd(); cd_to(shift); return ReleaseAction->new( sub {cd_to($cwd);} ); } # And a simple test system "pwd"; { my $var = temp_cd('/tmp'); system "pwd"; } system "pwd";
package ReleaseAction;

# Pass this a sub...
sub new {
  bless($_[1], $_[0]);
}

# and call it when it goes.
sub DESTROY {
  shift->();
}

1;