http://qs321.pair.com?node_id=151190

I must confess that I recently got burned by doing something stupid that is probably obvious to many folks that have written DESTROY methods for their objects.

A DESTROY I wrote was using backticks to execute a command to perform some additional cleanup (not something that I could do within perl unfortunately since somebody else wrote the binary). It looked something like this...

sub DESTROY { my $output = `some_additional_cleanup 2>&1`; ... }
The side effect of this is that executing a command like this alters $! and $? (usually by setting them to zero when the command works).

The problem occured in some code kind of like this...

my $obj = My::Object->new(); ... if ($!) { die "something bad happened: $!"; }
The die would work ok, and print ok, but just before the script exitted, the values of $! and $?, which die uses to determine the exit code, were being set to zero, so the exit code turned out to be zero as well. The calling script of course was examining the exit code and thought the child sucessfully completed, and broke (silently) as a result.

It turns out if I localize these in the DESTROY everything works ok...

sub DESTROY { local ($!, $?); my $output = `some_additional_cleanup 2>&1`; ... }
This may be mentioned in the perl docs, but I didn't seen anything after a quick look. Also, I'm not sure both of these need to be localized, perhaps someone can comment about this, but wanted to cover other possible error cases, so YMMV.

bluto