#!/usr/bin/perl
use strict;
use warnings;
open(STDOUT, '>', "outputfile.csv") or die "Can't redirect STDOUT: $!";
my %data;
sub read_csv {
my ($filename,$tag)=@_;
my $FILE;
my $raw=do {
open $FILE,'<',$filename or die "Could not open '$filename'! $!";
# discard the first lines (header)
<$FILE>;
# slurp the rest
local $/ =undef;
<$FILE>;
};
#Use $raw to read from
open $FILE,'<',\$raw;
while (<$FILE>) {
chomp;
my ($k,@value)= split /,/;
$data{$k}{$_}++ for @value;
}
close($FILE);
}
#Read in the data
read_csv('file3.csv');
#read_csv('file2.csv');
#read_csv('file1.csv');
#print STDOUT "Name\t\tAge\t\tCountry\t\tEthnic\t\tBloodgroup\tChange from\t", "\n";
print STDOUT join("\t\t", $_, sort keys %{$data{$_}}), "\n" for keys %data;</sup>
我得到的输出:
Dora 34 Arab B- Malaysia
Tudor 10 A+ Chinese Spain
Tharani 30 Australia Malay O-
Queeny 47 O+ Rusia Russian
Boszor 91 AB+ Chinese Mexico
Sarah 21 AB+ Bugis Malaysia
Szundi 23 AB- German Indian
预期输出:
Dora 34 Malaysia Arab B-
Tudor 10 Spain Chinese A+
Tharani 30 Australia Malay O-
Queeny 47 Rusia Russian O+
Boszor 91 Chinese Mexico AB+
Sarah 21 Bugis Malaysia AB+
Szundi 23 German Indian AB-
如何按顺序打印列?我的最后一篇专栏文章早些时候打印。这是为什么?我在以订单格式打印哈希元素时遇到问题。我想按字母顺序对我的专栏进行排序。
您将每一行存储为
{
Dora => 1,
34 => 1,
Malaysia => 1,
...
}
无法按照所需的顺序将它们取出。它根本不存在于该哈希中。
很容易修复。只需使用数组的哈希而不是哈希的哈希即可。
while ( <> ) {
next if $. == 1; # Skip header.
chomp;
my @fields = split( /,/, $_, -1 );
$data{ $fields[0] } = \@fields;
}
for my $id ( sort keys %data ) {
say join "\t", $data->{ $id }->@*;
}
备注:
$.
是最近读取的文件句柄的行号,因此 next if $. == 1;
会跳过标题行。-1
中的split( /,/, $_, -1 )
可防止空尾随字段丢失。除非...您希望行按原始顺序排列。那么为什么要存储它们呢?
while ( <> ) {
next if $. == 1; # Skip header.
chomp;
my @fields = split( /,/, $_, -1 );
say join "\t", @fields;
}