Reputation:
I'm trying for search in the one file for instances of the number and post if the other file contains those numbers
#!/usr/bin/perl
open(file, "textIds.txt"); #
@file = <file>; #file looking into
# close file; #
while(<>){
$temp = $_;
$temp =~ tr/|/\t/; #puts tab between name and id
@arrayTemp = split("\t", $temp);
@found=grep{/$arrayTemp[1]/} <file>;
if (defined $found[0]){
#if (grep{/$arrayTemp[1]/} <file>){
print $_;
}
@found=();
}
print "\n";
close file;
#the input file lines have the format of
#John|7791 154
#Smith|5432 290
#Conor|6590 897
#And in the file the format is
#5432
#7791
#6590
#23140
Upvotes: 2
Views: 165
Reputation: 5730
There are some issues in your script.
use strict;
and use warnings;
.
This would have told you about odd things in your script in advance.open( my $fh, '<', 'testIds.txt');
use autodie;
or check whether the opening worked.testIds.txt
into the array @file
but later on (in your grep
) you are
again trying to read from that file(handle) (with <file>
). As @PaulL said, this will always
give undef
(false) because the file was already read.|
with tabs and then splitting at tabs is not neccessary. You can split at the
tabs and pipes at the same time as well (assuming "John|7791 154" is really "John|7791\t154").|
's in it).With this in mind your script could be written as:
#!/usr/bin/perl
use strict;
use warnings;
# Open 'textIds.txt' and slurp it into the array @file:
open( my $fh, '<', 'textIds.txt') or die "cannot open file: $!\n";
my @file = <$fh>;
close($fh);
# iterate over STDIN and compare with lines from 'textIds.txt':
while( my $line = <>) {
# split "John|7791\t154" into ("John", "7791", "154"):
my ($name, $number1, $number2) = split(/\||\t/, $line);
# compare $number1 to each member of @file and print if found:
if ( grep( /$number1/, @file) ) {
print $line;
}
}
Upvotes: 3