简体   繁体   English

如何在perl中将一个文件的哈希键与另一个文件的哈希值进行比较

[英]how to compare a hash key of a one file with a hash value of another in perl

I have two files. 我有两个文件。 one file only contains key and another has key and value both. 一个文件只包含密钥,另一个文件包含密钥和值。 how could i compare a key of one file with value of another? 我怎么能比较一个文件的密钥和另一个文件的值?

  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

Here is what i have so far 这是我到目前为止所拥有的

    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;

You are reading one line from the first file and one line from the second line. 您正在读取第一个文件中的一行和第二行中的一行。 The problem is the lines do not have to be related. 问题是线条不必相关。 The classical solution is to read one file into a hash and then use the hash for lookup while reading the second one: 经典的解决方案是将一个文件读入散列,然后在读取第二个散列时使用散列进行查找:

#!/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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM