Perl:散列中数组的数组

use*_*627 2 arrays sorting perl hash numerical

我有一个数组哈希,我需要先在键上对它进行排序,然后对数组中的值进行排序.

这是我的简单代码:

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";     
   }
}
Run Code Online (Sandbox Code Playgroud)

但我得到以下输出:

col1 : col1 0.999
col2 : col2 0.899
col2 : col2 -0.52
col2 : col2 1.52
Run Code Online (Sandbox Code Playgroud)

因此键的排序很好,但值不是.我需要它们像这样出来:

col1 : col1 0.999
col2 : col2 -0.52
col2 : col2 0.899
col2 : col2 1.52
Run Code Online (Sandbox Code Playgroud)

我的代码出了什么问题?

Dav*_*oss 6

不确定为什么要构建哈希.您所需要的只是一个快速的Schwartzian变换.

#!/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;
Run Code Online (Sandbox Code Playgroud)

另外,使用名为$ lineX的变量有点红旗.您应该将这些值存储在数组中.