2013-11-25 91 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您通過點擊答案左側的複選框 –

相關問題