in reply to Reading a file before clobbering it for output...

I'm a bit confused by the if (1..10) statement, but I think I see what you're trying to do, put the newest log entry at the top of the text file, and limit the text file to 10 lines, correct? this will do the trick ( i was lazy and didn't flock, and the code naievely assumes $logfile exists already, but you get the idea. ) it just uses an array slice in the last foreach loop to limit the number of lines.

peace.

#!/usr/bin/perl -w use strict; my $log_string = "warning2 . . ."; my $logfile = "log.txt"; my @entries = (); my $entry; open LOG, "< $logfile" or die "cannot read $logfile"; @entries = <LOG>; map { chomp } @entries, $log_string; unshift @entries, $log_string; close LOG; open OUT, "> $logfile" or die "cannot write to $logfile"; foreach $entry ( @entries[0..9] ) { print OUT $entry."\n"; } close OUT;

Replies are listed 'Best First'.
Re: Re: Reading a file before clobbering it for output...
by Hofmator (Curate) on Jun 21, 2001 at 14:38 UTC

    I'm a bit confused by the if (1..10) statement

    This is the bistable operator, take a look at 'range operator' in perlop. Basically in scalar context a..b evaluates to false until condition a is met. Then it evaluates to true until condition b is met. If one of the expressions is constant (as is the case here) an implicit compare with $. (the current line number) takes place.

    -- Hofmator