<br><br><div><span class="gmail_quote">On 10/10/07, <b class="gmail_sendername">Jer A</b> <<a href="mailto:jeremygwa@hotmail.com">jeremygwa@hotmail.com</a>> wrote:</span><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
<br><br><br>hi all,<br><br><br>say I have an array of hashes pushed like so : push(@array, {key1 => 'test', string => 'this is a string', id => '1'});<br><br><br>how do i sort this alphabetically ascending or descending, by a specified key val, and still preserve the anonymous hash
<br><br>eg. after sorting, $array[$i]->{key1} and $array[$i]->{string} should be both from the same anon hash entry in the array.</blockquote><br>Hi,<br><br>I am still trying to fix my mail list settings to not use
digest, so if you already have a good answer, then I am sorry for the
repetition.
<br><br>Its hard to know what level you expect the sorting at via the
problem discription, but I am assuming you'd want to sort on keys at
the anon hashref level, and use the key/value pairing. This is how you
could do it (not including proper param validation):
<br><br>#######################################<br><div><br>#!/usr/bin/env/perl -w<br>use strict;<br><br>my @array = ({key => 'test', string => 'this is a string', id => 1 });<br><br>for my $href(@array) {
<br> for my $sorted (sort_this('asc', $href)) {<br> do_something($sorted, $href->{$sorted});<br> }<br> #This map could replace the for loop above; be warned about $_ in nested loops<br> #map { do_something($_, $href->{$_}); } sort_this('asc', $href);
<br>}<br><br>sub sort_this {<br> my ($direction, $href) = @_;<br> if ($direction eq 'desc') {<br> return reverse sort {$href->{$a} cmp $href->{$b}} keys %$href;<br> } elsif ($direction eq 'asc') {
<br> return sort {$href->{$a} cmp $href->{$b}} keys %$href;<br> } else {<br> die "A horrible death, or just use Params::Validate\n";<br> }<br>}<br><br>sub do_something {<br> my ($key, $val) = @_;
<br> print "key: $key \t val: $val\n";·<br>}<br><br>#####################################<br><br>Chuck</div></div><br>