use Scope::Guard qw(guard); { my @guards; for (keys %handler) { # Save the old state: my($k,$p) = ($_,\&$_); push @guards, guard { # restore the old state *$k = $p; }; # Install our new handler *$_ = \&$handler{$_}; } # "execute" the config # ... } # Scope::Guard executes our guard blocks here