I have a hash of arrays, and I need to sort it first on the keys, and then on the values in the array.
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
What's wrong with my code?
Not sure why you're building a hash. All you need is a quick Schwartzian Transform.
Also, having variables called $lineX is a bit of a red flag. You should probably store those values in an array.
Are you sure you want the
cols
string in the values again? If not, try this:Else, write the sort function for the second foreach to ignore the 'cols' word, and only use the second word for sorting.
Edit:
Well I wanted to evade writing that myself, but since you asked ;) this explains the gist: