2013-11-25 93 views
2

我有以下问题要解决......我有一个包含以下信息两个文件:比较两个文件并显示匹配结果

A.TXT

alan, 23, [email protected] 
albert, 27, [email protected] 

b.txt

alan:173:analyst 
victor:149:director 
albert:171:clerk 
coste:27:driver 

我需要从两个文件的每一行中提取名称(零字段),比较它们,如果它们匹配,则打印年龄和职业信息。 因此,我的输出应该是:

alan, 23, analyst 
albert, 27, clerk 

我有这么远,它不工作:

open F2, 'a.txt' or die $!; 
@interesting_lines = <F2>; 

foreach $line (@interesting_lines) { 
    @string = split(', ', $line); 
    print "$string[0]\n"; 
} 
close F2; 

open F1, 'b.txt' or die $!; 
while (defined(my $line = <F1>)) { 
    @string2 = split(':', $line); 
    print $string2[0]; 
    print "$.:\t$string2[0]" if grep {$string2[0] eq $_} $string[0] ; 
} 

有没有人有我如何能实现我的要求的任何想法?谢谢... Ps,bith文件可能比我发布的行更多,但文件b.txt将始终具有文件a.tx所具有的每个名称,以及额外的行。

回答

0
open my $F2, '<', 'a.txt' or die $!; 
chomp(my @interesting_lines = <$F2>); 
close $F2; 

my %dic; 
foreach my $line (@interesting_lines) { 
    my ($name, @arr) = split(/, /, $line); 
    $dic{$name} = \@arr; 
} 

open my $F1, '<', 'b.txt' or die $!; 

while (my $line = <$F1>) { 
    chomp($line); 
    my ($name, $pos) = (split(/:/, $line))[0, 2]; 

    my $arr = $dic{$name} or next; 
    printf("%s, %s, %s, %s\n", $name, $arr->[0], $pos, $arr->[1]); 
} 
close $F1; 
+0

非常感谢您的帮助:) –

+0

mpapec,非常感谢。是的,更新后的版本完美地工作。非常感谢。 –

+0

@WisdomSeeker您通过点击答案左侧的复选框 –

相关问题