1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@t = ( {'b','1','w','10'},{'b','3','w','30'},{'b','2','w','40'});
foreach $f1 (@t){
foreach $f2 (keys %$f1){
print $$f1{$f2},"\n";
}
}
@bb = sort func @t;
sub func{
print ${$a}{'b'}," ",${$a}{'w'}," :";
print ${$b}{'b'}," ",${$b}{'w'}," \n";
print "xxx",(${$a}{'b'} lt ${$b}{'b'}),"xxx";
print "\n================\n";
return ${$a}{'b'} lt ${$b}{'b'};
}
foreach $f1 (@bb){
foreach $f2 (keys %$f1){
print $$f1{$f2},"\n";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
10
1
30
3
40
2
1 10 :3 30
xxx1xxx
================
3 30 :2 40
xxxxxx
================
2 40 :1 10
xxxxxx
================
30
3
10
1
40
2
QuoteCan anybody enlighten me?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
use strict; use warnings; use Data::Dump qw(dump); #my @t = ( {'b','1','w','10'},{'b','3','w','30'},{'b','2','w','40'}); # at first, making hash readable as such my @t = ( {'b' => '1','w' => '10'},{'b' => '3','w' =>'30'},{'b' => '2','w' => '40'}); # consider issue: the value in key 'b' is numeric, use spaceship '<=>' for compare # transform by Randal Schwartz @t = map{$_->[0]} sort{$a->[1] <=> $b->[1]} map{ [$_, $_->{b}] }@t; print dump \@t;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
@t = ( {b=>1,w=>10}, {b=>3,w=>30}, {b=>2,w=>40}, {b=>7,w=>60}, {b=>4,w=>70}, {b=>6,w=>90}, {b=>5,w=>100}); print "## RAW #####################\n"; pout(@t); @bb = sort func @t; sub func{ return $a->{b} <=> $b->{b}; } print "## SORTED ##################\n"; pout(@bb); sub pout { foreach $f1 (@_){ foreach $f2 (sort keys %$f1){ print "$f2 $f1->{$f2}\n"; } print "------\n"; } }