我有两个文件。一个文件只包含密钥,另一个文件包含密钥和值。我如何将一个文件的密钥与另一个文件的值进行比较?
example of file1
steve
robert
sandy
alex
example of file2
age25, steve
age29, alex
age30, mindy
age50, rokuna
age25, steve
example of output
age25, steve
age29, alex
这是我到目前为止所拥有的
my $age_name="file1.txt";
my $name="file2.txt";
open my $MYFILE, "<", $name or die "could not open $name \n";
open my $MYFILE2, "<", $age_name or die "could not open $age_name \n";
while(<$MYFILE>) {
my ($key, $value) = split(",");
my $secondfile = <$MYFILE2>;
if ( defined $secondfile ) {
my ($key2, $value2) = split(",");
if ($value2=~m/$key/) {
print "$key2 - $value2 \n";
}
}
}
close $MYFILE;
close $MYFILE2;
答案 0 :(得分:2)
您正在读取第一个文件中的一行和第二行中的一行。问题是线条不必相关。经典的解决方案是将一个文件读入散列,然后在读取第二个散列时使用散列进行查找:
#!/usr/bin/perl
use strict;
use warnings;
my %age_of;
open my $AGE, '<', 'file2.txt' or die $!;
while (<$AGE>) {
chomp;
my ($age, $name) = split /, /;
$age_of{$name} = $age;
}
open my $NAME, '<', 'file1.txt' or die $!;
while (<$NAME>) {
chomp;
print "$age_of{$_}, $_\n" if exists $age_of{$_};
}