【发布时间】:2011-12-16 10:15:56
【问题描述】:
我有一个数组散列,我需要先对它的键进行排序,然后对数组中的值进行排序。
这是我的简单代码:
my %myhash;
$line1 = "col1 0.999";
$line2 = "col2 0.899";
$line3 = "col2 -0.52";
$line4 = "col2 1.52";
#insert into hash
@cols = split(" ", $line1);
push @{ $myhash{$cols[0]} }, $line1;
@cols = split(" ", $line2);
push @{ $myhash{$cols[0]} }, $line2;
@cols = split(" ", $line3);
push @{ $myhash{$cols[0]} }, $line3;
@cols = split(" ", $line4);
push @{ $myhash{$cols[0]} }, $line4;
foreach $k (sort {$a <=> $b} (keys %myhash)) {
foreach $v(sort {$a <=> $b}(@{$myhash{$k}}))
{
print $k." : $v \n";
}
}
但我得到以下输出:
col1 : col1 0.999
col2 : col2 0.899
col2 : col2 -0.52
col2 : col2 1.52
所以键排序很好,但值不是。我需要他们像这样出来:
col1 : col1 0.999
col2 : col2 -0.52
col2 : col2 0.899
col2 : col2 1.52
我的代码有什么问题?
【问题讨论】:
-
您的值包含
col2 1.52,其中包含 col2 值。这就是导致排序失败的原因。 -
为什么要在值中保留
colN名称?您需要什么类型的键(数字或字符串)? -
啊对!谢谢,我没有意识到这一点。
-
这就是为什么你应该总是使用“使用警告”。当 perl 大声抱怨这个错误时,错误就变得很明显了。
标签: arrays perl sorting hash numerical