user3507732
user3507732

Reputation: 5

How do you match strings from two files?

I always get this error "Use of uninitialized value $_ in print at finalhash.pl line 27, <$_[...]> line 7" when compiling this Perl code. But my example file doesn't have a line 7.

I want to print out the entire rows of file2.txt if the strings in first column matches with the strings in in second column of file1.txt.

The columns are separated by semicolons.

This code I adapted from another answer on a question I posted before (thanks to Borodin). Can someone tell me why in the first while loop the second column was given the value 1: "$wanted{$fields[1]} = 1;"?

use strict;
use warnings;
use autodie;

my $fh;
my %wanted;

open $fh, '<', 'file1.txt';
chomp $fh;
while (my $line = <$fh>) {

    my @fields = split(';', $line);

    $wanted{$fields[1]} = 1;

}


open $fh, '<', 'file2.txt';
chomp $fh;
while (my $line = <$fh>) {

my @fields = split(';', $line);

   print if $wanted{$fields[0]};  #line 27 with the error


}

close $fh;

Upvotes: 0

Views: 437

Answers (1)

Chris Charley
Chris Charley

Reputation: 6573

open $fh, '<', 'file1.txt';
#chomp $fh;
while (my $line = <$fh>) {
    chomp $line;


open $fh, '<', 'file2.txt';
#chomp $fh;
while (my $line = <$fh>) {

With these changes, your script should run fine. In the first file read, you didn't 'chomp' $line. chomp $fh is meaningless - does nothing.

No need to remove the newline in file 2, because you are just going to print it out later.

Update: Matt got the problem in the comments above. print $line if ...

Upvotes: 1

Related Questions