的Perl:在哈希数值排序阵列 [英] Perl: Numerical sort of arrays in a hash
本文介绍了的Perl:在哈希数值排序阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有数组的哈希值,我需要在按键排序第一,然后在数组中的值。
I have a hash of arrays, and I need to sort it first on the keys, and then on the values in the array.
下面是我简单的code:
Here's my simple code:
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";
}
}
不过,我得到以下输出:
But I get the following output:
col1 : col1 0.999
col2 : col2 0.899
col2 : col2 -0.52
col2 : col2 1.52
所以按键排序罚款,但价值都没有。我需要他们出来是这样的:
So the keys are sorted fine, but the values aren't. I need them to come out like this:
col1 : col1 0.999
col2 : col2 -0.52
col2 : col2 0.899
col2 : col2 1.52
这有什么错我的code?
What's wrong with my code?
推荐答案
不知道为什么你正在构建一个哈希值。所有你需要的是一个快速的Schwartzian变换。
Not sure why you're building a hash. All you need is a quick Schwartzian Transform.
#!/usr/bin/perl
use strict;
use warnings;
my $line1 = "col1 0.999";
my $line2 = "col2 0.899";
my $line3 = "col2 -0.52";
my $line4 = "col2 1.52";
my @sorted = map { join ' ', @$_ }
sort { $a->[0] cmp $b->[0] or $a->[1] <=> $b->[1] }
map { [ split ] } ($line1, $line2, $line3, $line4);
print "$_\n" for @sorted;
另外,其变量名为$ LINEX是有点红旗。你应该这些值可能存放在数组中。
Also, having variables called $lineX is a bit of a red flag. You should probably store those values in an array.
这篇关于的Perl:在哈希数值排序阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文