timestamp in STDERR output

Matthew Lawrence matthew.lawrence at ehsbrann.com
Fri Jun 30 11:36:20 BST 2006


ben fitzgerald wrote:
> On Jun 29, 2006 03:19 PM, David Cantrell <david at cantrell.org.uk> wrote:
> 
> 
>>On Thu, Jun 29, 2006 at 04:02:46PM +0200, Thomas Busch wrote:
>>
>>
>>>is it possible to redefine STDERR in such a way that
>>>you get a timestamp at the beginning of each line ?
>>
>>#!/usr/bin/perl
>>use strict;
>>use warnings;
>>
>>use Tie::STDERR \&timestamper;
>>
>>sub timestamper {
>>    local *STDERR;
>>    untie *STDERR;
>>    print time().': '.$_[0];
>>}
> 
> 
> hi thomas,
> 
> I'm trying to understand perl a little better here!
> 
> could you explain why you use untie here having used the typeglob to
> make the STDERR filehandle local to the block?
> 
> does this have a similar effect to select in this case as you print to
> the default filehandle?

It's bypassing the tie() magic (and therefore avoiding an infinite loop
when you print to STDERR), while ensuring that the original, tied STDERR
is re-instated at the end of the block.

sub timestamper {
    # Make our own copy of STDERR to use in this sub
    local *STDERR;

    # ensure that print STDERR doesn't call timestamper()
    untie *STDERR;

    # now we can print to STDERR without and tie magic
    print STDERR time() . ": ', $_[0];

    # end of scope of our local STDERR,
    # future writes to STDERR will invoke timestamper
}


See also:

http://search.cpan.org/author/JANPAZ/Tie-STDERR-0.26/STDERR.pm

Matt


More information about the london.pm mailing list