in reply to grep and delete
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
|
|---|