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

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.