This sounds like a good job for Tie::File. (the following is untested.)

use strict; use warnings; use Tie::File; my @array; tie @array, 'Tie::File', 'filename.txt' or die $!; foreach ( 0 .. $#array ) { if( $array[$_] =~ /word/ ) { $#array = ( $_ < $#array ) ? $_ + 1 : $_; last; } } untie @array;

This works by iterating over the array tied to the file. When 'word' is found, the array is resized (by setting $#array to a smaller value). An extra check is done to ensure that if 'word' is found on the last line of the array we're not resizing the array larger than it previously was. The one inefficiency here is that behind the scenes Tie::File must learn how many lines there are in the array, and that means scanning through the file internally first. In practice it doesn't seem to slow things down noticably, but I suppose for super large files it could.

I often overlook Tie::File, thinking of it as mostly a novelty; not really something you would think of actually using. But I shouldn't think of it that way; it works, it's fast, and it makes some simple tasks even simpler.


Dave


In reply to Re: grep and delete by davido
in thread grep and delete by Anonymous Monk

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.