my $fileName= "toBeTrimmed.txt"; open( FILE, "+< $fileName" ) or die "Can't update $fileName: $!\n"; my $readPos= tell(FILE); my $writePos; while( ) { if( wantLine($_) ) { $readPos= tell(FILE) or die "Can't tell after read: $!\n"; if( defined($writePos) ) { seek( FILE, $writePos, 0 ) or die "Can't seek to write: $!\n"; print FILE $_ or die "Failed writing to file: $!\n"; $writePos= tell(FILE) or die "Can't tell after write: $!\n"; seek( FILE, $readPos, 0 ) or die "Can't seek to read: $!\n"; } } elsif( ! defined($writePos) ) { $writePos= $readPos; } } if( defined($writePos) ) { truncate( FILE, $writePos ) or warn "Can't truncate: $!\n"; }