<br><br><div><span class="gmail_quote">On 10/10/07, <b class="gmail_sendername">Jer A</b> &lt;<a href="mailto:jeremygwa@hotmail.com">jeremygwa@hotmail.com</a>&gt; 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 =&gt; &#39;test&#39;, string =&gt; &#39;this is a string&#39;, id =&gt; &#39;1&#39;});<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]-&gt;{key1} and&nbsp;&nbsp;$array[$i]-&gt;{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&#39;d want to sort on keys at
the anon hashref level, and use the key/value pairing.&nbsp; 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 =&nbsp; ({key =&gt; &#39;test&#39;, string =&gt; &#39;this is a string&#39;, id =&gt; 1 });<br><br>for my $href(@array) {
<br>&nbsp;&nbsp;&nbsp; for my $sorted (sort_this(&#39;asc&#39;, $href)) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; do_something($sorted, $href-&gt;{$sorted});<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; #This map could replace the for loop above; be warned about $_ in nested loops<br>&nbsp;&nbsp;&nbsp; #map { do_something($_, $href-&gt;{$_}); } sort_this(&#39;asc&#39;, $href);
<br>}<br><br>sub sort_this {<br>&nbsp;&nbsp;&nbsp; my ($direction, $href) = @_;<br>&nbsp;&nbsp;&nbsp; if ($direction eq &#39;desc&#39;) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return reverse sort {$href-&gt;{$a} cmp $href-&gt;{$b}} keys %$href;<br>&nbsp;&nbsp;&nbsp; } elsif ($direction eq &#39;asc&#39;) {
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return sort {$href-&gt;{$a} cmp $href-&gt;{$b}} keys %$href;<br>&nbsp;&nbsp;&nbsp; } else {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; die &quot;A horrible death, or just use Params::Validate\n&quot;;<br>&nbsp;&nbsp;&nbsp; }<br>}<br><br>sub do_something {<br>&nbsp;&nbsp;&nbsp; my ($key, $val) = @_;
<br>&nbsp;&nbsp;&nbsp; print &quot;key: $key \t val: $val\n&quot;;·<br>}<br><br>#####################################<br><br>Chuck</div></div><br>