The script I have written outputs all lines from the file 2 that starts with a number that is in the file 1.
Question
How do I output all the other lines that didn’t matched?
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @res;
open(FILE, '<', "1") or die $!;
while (defined (my $line = <FILE>)) {
chomp $line;
push @res, $line;
}
close FILE;
open(FILE, '<', "2") or die $!;
while (defined (my $line = <FILE>)) {
chomp $line;
$line =~ m/(\d+)/;
if (defined $1) {
foreach my $a (@res) {
if ($a == $1) {
print $line . "\n";
}
}
}
}
close FILE;
File 1
155
156
157
158
159
160
File 2
150 a
151 f
152 r
153 a
154 a
155 a
156 a
157 f
158 f
159 f
Your answer is pretty close actually: it’s enough to change this
… to this …
Yet still there’s something to talk about. ) See, as all these number strings in the first file are unique, it’s much better to use a hash for storing them. The code will actually not change that much:
But the point is that searching in hash is MUCH faster than looping through an array again and again. )