CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate: sorting by element of an array within a hash: Edit Log



lilmark
New User

Mar 1, 2013, 9:05 AM


Views: 751
sorting by element of an array within a hash

 I'm having trouble sorting by the PERCT1 element in descending order. What I attempted to do below was...

-store the month as the key for %MMT and the rest of the data as the value

-store the month as the key for %MMTsort and PERCT1 as the value

-this will create both Hashes in the same order

-then sort %MMTsort by its value/PERCT1 in descending order and use the returned location/index of the element to print out %MMT in the proper order



But it's not working. It's still printing it out in the same order it was store into the hash. Anyone see what I am overlooking?



open FP, "$fn1" || die "Cannot open $fn1\n";
while (chomp($r=<FP>))
{
$r=~s/\r//;
@arr=split /\t/, $r;
next if $arr[1] eq "Total";
@arr2=($arr[1], $arr[2], $arr[3], $arr[4], $arr[5]);
push @{ $MMT{$arr[0]} }, [@arr2];
push @{ $MMTsort{$arr[0]} }, $arr[2];
}
close FP;
foreach $yrmo (sort keys %MMT)
{
@b=(0..$#{$MMTsort{$yrmo}});
print "yrmo=$yrmo\n";
foreach $index (sort byMOM @b)
{
printf "%s\n", join "\t", @{$MMT{$yrmo}[$index]};
}
print "\n";
}



MONTH GROUPS PERCT1 NMBR CNT PERCT2
201302 GROUP_1 0.44 201 6,000 0.91
201302 GROUP_2 0.42 192 10,806 1.65
201302 GROUP_3 0.38 159 4,065 0.62
201303 GROUP_11 0.15 -474 4,691 0.58
201303 GROUP_15 0.08 -209 3,010 0.37
201303 GROUP_13 0.05 -93 9,879 1.22
201304 GROUP_12 0.04 184 10,977 2.13
201304 GROUP_4 0.00 91 9,184 1.78
201304 GROUP_5 -0.01 87 14,042 2.72
201305 GROUP_15 0.35 47 3,667 0.71
201305 GROUP_10 0.34 44 8,961 1.74
201305 GROUP_7 0.30 26 8,130 1.58




I managed to make it work using the below code of arrays, but I'm assuming I'm not doing something wrong when involving the hash.

my $c=1;
@{$a[1]}=(2,7,5,4,6,9,8,1,3);

@b=(0..$#{$a[1]});

sub byMOM{
$a[$c][$b]<=>$a[$c][$a];}


print "@b\n";
0 1 2 3 4 5 6 7 8
printf "%s\n", join "\n", sort byMOM @b;
5
6
1
4
2
3
8
0


(This post was edited by lilmark on Mar 1, 2013, 9:09 AM)


Edit Log:
Post edited by lilmark (New User) on Mar 1, 2013, 9:09 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives