Search code examples
fileperl

perl remove inexistence path from text file


I would like to read the path from a text file, and check if the path existing. If the path exists, remain the entry in the file, else removed from the same file. Below code is buggy where some of the existing entry got removed as well

use strict;
use warnings;
my $file="/path/to/file.txt";
my @new_line_list;
open(FH1, "<", $file ) or die "Can't open file for reading: $!"; 
while(my $line = <FH1>){
   chomp $line;
    next if (!-d $line);
    @new_line_list=$line;
}
close( FH1 ); 
        
# Rewrite file with the line removed
open(FH2, ">", $file ) or die "Can't open file for reading: $!"; 
   foreach my $line ( @new_line_list) { 
       print FH2 $line; 
   } 
    close(FH2); 

Solution

  • The problem is here:

    @new_line_list=$line;
    

    You're overwriting the list of lines every time. Instead, use push:

    push @new_line_list, $line;
    

    Another option would be to write to a different file and rename it over the original file when done.