[英]how to compare a hash key of a one file with a hash value of another in perl
我有兩個文件。 一個文件只包含密鑰,另一個文件包含密鑰和值。 我怎么能比較一個文件的密鑰和另一個文件的值?
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;
您正在讀取第一個文件中的一行和第二行中的一行。 問題是線條不必相關。 經典的解決方案是將一個文件讀入散列,然后在讀取第二個散列時使用散列進行查找:
#!/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{$_};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.