Minimally tested:

use strict; use File::Basename; errlog_on(); warn "$0 started ". localtime() . $/; warn; errlog_rotate(); warn; # ... { my ( $errlog_file, $orig_stderr ); INIT { our ( $prog, $path ) = fileparse( $0, '.pl' ); $errlog_file = "${path}${prog}.err"; } sub errlog_on { $orig_stderr and defined fileno $orig_stderr or open $orig_stderr, '>&', STDERR or die "Failed to dup STDERR"; open STDERR, '>>', $errlog_file or die "invisible error"; } sub errlog_off { return unless defined fileno STDERR; defined fileno $orig_stderr or die "Can't find original STDERR\n"; close STDERR or die "failed to close $errlog_file"; open STDERR, '>&', $orig_stderr or die "Can't restore STDERR\n"; close $orig_stderr or die "failed to close STDERR dup\n"; } sub errlog_rotate { errlog_off(); log_rotate( $errlog_file ); # backs up $errlog_file # and truncates it; dies # on failure errlog_on(); } }

Update: Fixed a few bugs. In particular, I followed my own advice and used File::Basename to parse the name of the script (for reasons I did not bother to investigate further, the regex in the original code, which I simply copied for this snippet, was producing wrong values for $path and $prog). Also added a check to ensure that $orig_stderr was defined before applying fileno to it (fileno on undef is fatal).

the lowliest monk


In reply to Re: Getting around a possible file lock by tlm
in thread Getting around a possible file lock by punkish

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.