user6131143
user6131143

Reputation:

My perl script isn't working, I have a feeling it's the grep command

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

Answers (1)

PerlDuck
PerlDuck

Reputation: 5730

There are some issues in your script.

  1. Always include use strict; and use warnings;. This would have told you about odd things in your script in advance.
  2. Never use barewords as filehandles as they are global identifiers. Use three-parameter-open instead: open( my $fh, '<', 'testIds.txt');
  3. use autodie; or check whether the opening worked.
  4. You read and store 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.
  5. Replacing | 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").
  6. Your talking about "input file" and "in file" without exactly telling which is which. I assume your "textIds.txt" is the one with only the numbers and the other input file is the one read from STDIN (with the |'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

Related Questions