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,如需转载请自行联系原作者