0

我有两个文件。一个文件只包含键,另一个文件同时具有键和值。我如何将一个文件的键与另一个文件的值进行比较?

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

1 回答 1

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{$_};
}
于 2012-05-30T21:59:12.720 回答