Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I can't get the following script to work. I'm probably overlooking something super obvious, but I can't grok it this morning.

What I want to do is have an ongoing log file, where I can enter a comment, and have that comment timestamped. Any tips appreciated.

use strict; use warnings; use Data::Dumper; my ($sec,$min,$hour,$mday,$mon,$year,$wday, $yday,$isdst)=localtime(time); my $table; my $log = 'log_file.txt'; open my $fh, '>>', $log or die "Can't open $log : $!"; while (<$fh>) { my $comment = <STDIN>; chomp $comment; printf "%4d-%02d-%02d %02d:%02d:%02d\t", $year+1900,$mon+1,$mday,$hour,$min,$sec; print $comment . "\n"; printf $fh "%4d-%02d-%02d %02d:%02d:%02d\t", $year+1900,$mon+1,$mday,$hour,$min,$sec; print $fh $comment . "\n"; } close $fh;

Replies are listed 'Best First'.
Re: script for adding timestamp to stdin
by Old_Gray_Bear (Bishop) on Jun 02, 2010 at 17:21 UTC
    You opened the file for append (with '>>') and then use it as input (while (<$fh>) {), which gives you and immediate EOF....

    ----
    I Go Back to Sleep, Now.

    OGB

Re: script for adding timestamp to stdin
by vtheron (Novice) on Jun 02, 2010 at 18:10 UTC
    You're looping on input from your log file. I expect that you meant to loop on input from STDIN. Also, you need to update your timestamp variables inside the loop. Try this:
    use strict; use warnings; use Data::Dumper; my $table; my $log = 'log_file.txt'; open my $fh, '>>', $log or die "Can't open $log : $!"; while (<STDIN>) { my $comment = $_; chomp $comment; my ($sec,$min,$hour,$mday,$mon,$year,$wday, $yday,$isdst)=localtime(time); printf "%4d-%02d-%02d %02d:%02d:%02d\t", $year+1900,$mon+1,$mday,$hour,$min,$sec; print $comment . "\n"; printf $fh "%4d-%02d-%02d %02d:%02d:%02d\t", $year+1900,$mon+1,$mday,$hour,$min,$sec; print $fh $comment . "\n"; } close $fh;
      thanks -- but the log file is not being updated still... why is that? We have a file handle, we're printing to it... er...

        Try

        open my $fh, ... use IO::Handle; $fh->autoflush(); # <--

        File handles are block-buffered by default, i.e. output is not flushed/written to the file until the buffer is full.

Re: script for adding timestamp to stdin
by almut (Canon) on Jun 02, 2010 at 17:33 UTC
    What I want to do is have an ongoing log file, ...

    What exactly is the intention, i.e. why are you trying to read/write from/to the end of the same file?  Why the reading?