roboticus's example is a script that reverses itself (it opens $0), and it was run first, then printed, so it came out in reverse :-)
seek works in bytes, not characters or lines. You understood correctly that you can use it to move the current position around in the file (relative to its beginning, the current position, or its end). truncate cuts down the file to a certain size (AFAIK also in bytes, definitely not lines), but always from the beginning of the file.
I understand you want to preserve the first line of the file. You could do that by figuring out where that line ends (in bytes!), and truncate the file to there. However, since we're only talking about one line here, the logic would be much easier if you just clobber the entire file, modify the array of lines, and write everything back out.
my $MAXLINES=20; # not including header open my $fh, '+<', 'foo.txt' or die $!; my @lines = <$fh>; splice @lines, 1, @lines-$MAXLINES if @lines>$MAXLINES; push @lines, "newline\n"; truncate $fh, 0 or die "truncate failed"; seek $fh, 0, 0 or die "seek failed"; print $fh @lines; close $fh;
But I would also second dasgar's suggestion for Tie::File.
use Tie::File; my $MAXLINES=20; # not including header tie my @lines, 'Tie::File', 'foo.txt' or die "tie failed"; splice @lines, 1, @lines-$MAXLINES if @lines>$MAXLINES; push @lines, "newline\n"; untie @lines;
In reply to Re^2: Capture Contents AND Overwrite without Opening Twice?
by Anonymous Monk
in thread Capture Contents AND Overwrite without Opening Twice?
by mmartin
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |