Perl script grep

2019-09-17 19:56发布

问题:

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";

回答1:

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.



标签: perl grep