0

The script is printing the amount of input lines, I want it to print the amount of input lines that are present in another file

#!/usr/bin/perl -w
open("file", "text.txt"); 
        @todd = <file>;         
        close "file";
while(<>){
        if( grep( /^$_$/, @todd)){
        #if( grep @todd, /^$_$/){
                print $_;
        }
        print "\n";
}

if for example file contains

1
3
4
5
7

and the input file that will be read from contains

1
2
3
4
5
6
7
8
9

I would want it to print 1,3,4,5 and 7 but 1-9 are being printed instead

UPDATE****** This is my code now and I am getting this error readline() on closed filehandle todd at ./may6test.pl line 3.

#!/usr/bin/perl -w
open("todd", "<text.txt");
        @files = <todd>;         #file looking into
        close "todd";
while( my $line = <> ){
        chomp $line;
        if ( grep( /^$line$/, @files) ) {
                print $_;
        }
        print "\n";
}

which makes no sense to me because I have this other script that is basically doing the same thing

#!/usr/bin/perl -w
open("file", "<text2.txt");    #
        @file = <file>;         #file looking into
        close "file";           #
while(<>){
        $temp = $_;
        $temp =~ tr/|/\t/;      #puts tab between name and id
        my ($name, $number1, $number2) = split("\t", $temp);
        if ( grep( /^$number1$/, @file) ) {
                print $_;
        }
}
print "\n";
2
  • 2
    This is almost the same Q as this one posed 3hrs ago. If you are the same person I strongly recommend not to double post from different accounts. Else I recommend to look out for the very same questions already posted on SO. Commented May 6, 2016 at 22:28
  • Rule of thumb: avoid using $_ implicitly or explicitly for exactly this reason. map and grep are exceptions because its use is required. Commented May 7, 2016 at 0:21

1 Answer 1

5

OK, the problem here is - grep sets $_ too. So grep { $_ } @array will always give you every element in the array.

At a basic level - you need to:

while ( my $line = <> ) { 
   chomp $line; 
   if ( grep { /^$line$/ } @todd ) { 
      #do something
   }
}

But I'd suggest instead that you might want to consider building a hash of your lines instead:

open( my $input, '<', "text.txt" ) or die $!;
my %in_todd = map { $_ => 1 } <$input>;
close $input;
while (<>) {
   print if $in_todd{$_};
}

Note - you might want to watch for trailing linefeeds.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.