I recently posted a question asking for help in sorting an array of hashes by the values of multiple hash keys. I generally received answers relating to the sort function, which at first glance appeared to work. However, a closer look revealed that the nature of the sort function causes any new sort done on something previously sorted causes all order from the previous sort to be discarded. I came up with the following to get around this problem. I'd be very interested to hear comments, and suggestions for improvement.
sub sorthasharray($$) { # takes reference to array of hashes, and arra
+y of key names to sort by.
my ($hasharray, $keylist) = @_;
my $keyCount; # counter
my $hashCount; # counter
for $hashCount ( 0 .. $#$hasharray ) { # walk through the arr
+ay
for $keyCount ( 0 .. $#$keylist ) { # walk through the
+ keys
if ( $$hasharray[$hashCount]{$$keylist[$keyCou
+nt]} =~ /^\d*?\.??\d*?$/ ) { # check to see if this should be a nume
+ric comparison
my $zeros = 12 - (length($$hasharray[$
+hashCount]{$$keylist[$keyCount]})); # find out how many zeros we nee
+d
#to pad to the right to make a string comparison equivalent to a numer
+ic comparison
#(this isn't onehundred percent accurate, especially for float numbers
+. Anyone want to take a crack at it?
for $zeroCount ( 1 .. $zeros ) {
$$hasharray[$hashCount]{sortke
+y} .= "0"; # padd the zeros
}
}
$$hasharray[$hashCount]{sortkey} .= $$hasharra
+y[$hashCount]{$$keylist[$keyCount]}; # build sortkey by concatenatin
+g all sort keys in order
}
}
@$hasharray = sort { $$a{sortkey} cmp $$b{sortkey} } @$hasharr
+ay; # do the sort
for $hashCount ( 0 .. @$hasharray ) {
delete $$hasharray[$hashCount]{sortkey}; # delete the
+ unneeded key from all the hashes
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.