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


In reply to Devious destructor by bluto

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.