linuxtone上某位童鞋的面試題目,檔案如下
品牌 産品編号 價格
A 001 10
A 002 20
A 003 30
B 004 40
B 005 50
C 006 60
C 007 70
要求得到如下結果
A産品編号 A價格 B産品編号 B價格 C産品編号 C價格
001 10 004 40 006 60
002 20 005 50 007 70
003 30
啥也不說,直接上perl代碼
#!/usr/bin/perl -w
use strict;
#定義一個空的哈希表
my %hash = ();
open my $file,'<','a.txt' or die "$!\n";
while ( <$file> ) {
chomp;
#過濾掉檔案第一行所在的漢字部分
next if /品牌/;
my @array = split /\s+/;
$hash{$array[0]} = [] unless exists $hash{$array[0]};
#數組引用
push @{$hash{$array[0]}},"$array[1]\t\t$array[2]";
}
close $file;
#周遊出哈希的鍵值
for my $prod ( sort keys %hash ) {
#解引用
my @tmp_array = @{$hash{$prod}};
#輸出結果
print "${prod}産品編号\t${prod}價格\n";
print join "\n",@tmp_array;
print "\n";
這個代碼輸出的格式并沒有與要求的一樣,有興趣的自己改下,知道怎麼用perl處理就好,我覺得這才是關鍵
output:
[root@test henry]# perl a.pl
A産品編号 A價格
001 10
002 20
B産品編号 B價格
004 40
005 50
C産品編号 C價格
006 60
007 70
本文轉自dongfang_09859 51CTO部落格,原文連結:http://blog.51cto.com/hellosa/580763,如需轉載請自行聯系原作者