In addition to what chromatic said, you can do this:

#!/usr/bin/perl -w use strict; BEGIN { open( ERRORLOG, ">> /tmp/test_error.log" ) || die $!; } END { close( ERRORLOG ); } { $SIG{__WARN__} = sub { print ERRORLOG 'warn - ' . $_[0] }; $SIG{__DIE__} = sub { print ERRORLOG 'die - ' . $_[0] }; warn "Hey I told you so with that warning"; eval { die "Blah! It's a die command! that goes here" }; print "dingle dongle goes here\n" }

Output is:

dingle dongle goes here

And contents of error.log are:

warn - Hey I told you so with that warning at test_sigdie.pl line 15. die - Blah! It's a die command! that goes here at test_sigdie.pl line + 16.

Note that die will still die if you don't wrap it in an eval {}. Also, since it's not installed yet the signal handler doesn't catch the die in the BEGIN block, so you don't need to worry about any bad things happening there. And also note that you can re-throw a warn or die from within the signal handler without getting into an infinite loop.

Redirecting error messages like this is really nifty, but once you get into using larger programs you need to be careful about doing this. Other modules might depend on die acting the normal way, so when you start throwing (for instance) hashrefs everywhere instead of plaintext you can run into some trouble. (At least, I thought I ran into trouble doing this, but maybe I just wasn't smart enough to get myself out of it :)


In reply to RE: A couple of problems.... by lachoy
in thread A couple of problems.... by djw

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.