Hi everyone, i have done create a script where a portion of the script will search through a file (line by line) in comparison of an array. The end goal of this portion is to flag out "error message" if there is no such element from the array in the file that i am searching.
I try to solve this using two different ways of looping through a file and i found the solution by choosing the 1st method
My Question is there any other preferred solution to solve this?
I do paste a snippet of my code and the generated output here for reference.The first method
use strict; use warnings; use Getopt::Long; my ($cfg,$files,$output); $output = 'Output.summary'; GetOptions ('cfg=s' => \$cfg, 'rtl=s' => \$files); open my $fh1, '<', $cfg or die "Can't open $cfg: $!"; open my $fh2, '<', $files or die "Can't open $files: $!"; open my $fh3, '>', $output or die "Can't open $output: $!"; my @array_1 = <$fh2>; my ($element); my ($data_1,$data_2,$data); my %hash ; while (<$fh1>) { $data = $_; chomp $data; next unless /\S/; foreach $element(@array_1) { next unless /\S/; chomp $element; if ($element =~ quotemeta($data)) { $hash{$data} = "$data exist_1"; last; } else { $hash{$data} = "$data doesn't exist"; } } } while (my($key,$value) = each(%hash)) { print $fh3 "$key => $value\n"; }
Second method (edit the following lines only)
my @array_1 = <$fh1>; while (<$fh2>) { if ($data =~ quotemeta($element)) { $hash{$element} = "$element exist_1"; last; } else { $hash{$element} = "$element doesn't exist"; } } }
Output for the 1st method followed by the 2nd method
xdrvo[93] => xdrvo[93] exist_1 x106_in => x106_in exist_1 hlkout => hlkout exist_1 xdrvo[63] => xdrvo[63] exist_1 v7drvo0 => v7drvo0 exist_1 xdrvo[1002] => xdrvo[1002] doesn't exist xdrvo[95] => xdrvo[95] doesn't exist x95_in => x95_in exist_1
2nd one
Thank you in advance for all the folks out there who will reply and help to explain on this. From my opinion, one key point to consider is the line number differences for the cfg_file and the main file(where it search line by line).xdrvo[93] => xdrvo[93] doesn't exist x106_in => x106_in doesn't exist hlkout => hlkout doesn't exist xdrvo[63] => xdrvo[63] doesn't exist v7drvo0 => v7drvo0 doesn't exist xdrvo[1002] => xdrvo[1002] doesn't exist xdrvo[95] => xdrvo[95] doesn't exist x95_in => x95_in doesn't exist </p>
In reply to Looping two files differently by noob_mas
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |