in reply to Delete Lines Across Multiple Files

It looks to me like the pieces of code relating to $process_file and $process_file2 are basically identical, which means you can simply do the same thing in a loop. Note you've got a stray . on the second-to-last line of your code, and the multiple close $process_file statements don't make sense, as those variables hold the file names, not handles.

for my $process_file ($rrconfig::locodata, $rrconfig::availlocodata) { open(my $data_file_handle, '<', $process_file) or die("$process_fi +le: $!"); my @data = <$data_file_handle>; close($data_file_handle); chomp(@data); open(my $out_file_handle, '>', $process_file) or die("$process_fil +e: $!"); foreach my $line_from_file ( @data ) { my @field = split( /\:/, $line_from_file ); next if( ($field[1] eq $delroad) && ($field[2] == $delnumber) +); print $out_file_handle $line_from_file, "\n"; } close $out_file_handle; }

Although I feel like I've been plugging it pretty often lately, note this code can be simplified using inplace editing, using either $^I (an example, but note that -i has a few caveats like in some cases only issuing a warning when something goes wrong, instead of dying), or my module File::Replace. This has the advantage of not having to load the entire file into memory, like the code above does.

use File::Replace 'replace3'; for my $process_file ($rrconfig::locodata, $rrconfig::availlocodata) { my ($infh, $outfh, $repl) = replace3($process_file); while ( my $line = <$infh> ) { chomp($line); my @field = split( /\:/, $line ); next if ($field[1] eq $delroad) && ($field[2] == $delnumber); print $outfh $line, "\n"; } $repl->finish; }

Replies are listed 'Best First'.
Re^2: Delete Lines Across Multiple Files
by PilotinControl (Pilgrim) on Dec 31, 2020 at 17:26 UTC

    @haukex: thanks for the advice I will try that. If I load 3 files and the data is only in 2 files will my 3rd file become blank? or will it be left alone? Thanks!

      If I load 3 files and the data is only in 2 files will my 3rd file become blank? or will it be left alone?

      The code you wrote, which I just put in the loop, just does this: split the line on colons, check if the second and third fields match certain values and if yes skip that line via next, otherwise write the line back out via print. In other words, it will delete the lines that match the condition, all the other lines remain unchanged. This is true for any file the code processes. This is the advantage of the loop, you know every file will be treated exactly the same - unless of course there's a fatal error on one of the files, in which case the rest won't be processed, but there are ways to handle that too.

      Minor edits.