Thread How to sort Array with hashref Elements and custom search function (5 answers)
Opened by Frank Schuster at 2011-04-14 17:58

Gast Frank Schuster
 2011-04-14 17:58
#147763 #147763
Hi.

I want to sort the hasref elements of the array @t in the way that the value from the key 'b' in each anonyme hash should be considered in the sorting process. The result shoud be an array with following order:
( {'b','1','w','10'},{'b','2','w','40'},{'b','3','w','30'}).

Code: (dl )
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";
}
}


The curios result output of my checking statements is the following:
Code: (dl )
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


Why there is just one output of the comparing process ( 1 surrounded by xxx)?

Can anybody enlighten me?

Regards.

mcfaq
Last edited: 2011-04-14 18:12:09 +0200 (CEST)

View full thread How to sort Array with hashref Elements and custom search function