Perl Issue: contents deleted after grep

Viewed 50

I see the contents of file deleted after perl grep, any reason/fix? I need to take decision if grep is success or not.

open my $fh, "<", $file or die "can't read open '$file': $OS_ERROR";
$start_sync=0;
if (grep{/PATTERN/} <$fh>){
    print "word found\n";
    $start_sync=1;
}
else{
    print "word not found\n";
    $start_sync=0;
}
my @lines = <$fh>;  
close $fh or die "can't read close '$file': $OS_ERROR";  
if($start_sync==1) {edit the same file}

While the grep itself is working, the contents of the file is blanked/deleted after the grep. Without the grep, this deletion doesnt happen. Wondering what causes the contents to be blanked out.

2 Answers

When you call <$fh> as the second argument of grep, it forces list context on the diamond operator, which reads all the lines from the file. When the grep finishes, the filehandle is exhausted and points to eof.

If you want to read the file again, you need to rewind the filehandle position. Use seek for that:

seek $fh, 0, 0;
my @lines = <$fh>;

or if you love readable code,

use Fcntl ':seek';
# ...
seek $fh, 0, SEEK_SET;

The grep will process all of the elements, so it will look at every line even if you already have your answer. But what if you find it on line 1 of a billion lines? Instead, loop until you find it then stop:

while( <$fh> ) {
    next unless /PATTERN/;
    $start_sync = 1;
    last;
    }
Related