[VPM] sort array of anon hashes

Charles Frank charlespfrank at gmail.com
Wed Oct 10 21:14:12 PDT 2007


On 10/10/07, Jer A <jeremygwa at hotmail.com> wrote:
>
>
>
>
> hi all,
>
>
> say I have an array of hashes pushed like so : push(@array, {key1 =>
> 'test', string => 'this is a string', id => '1'});
>
>
> how do i sort this alphabetically ascending or descending, by a specified
> key val, and still preserve the anonymous hash
>
> eg. after sorting, $array[$i]->{key1} and  $array[$i]->{string} should be
> both from the same anon hash entry in the array.


Hi,

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.

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):

#######################################

#!/usr/bin/env/perl -w
use strict;

my @array =  ({key => 'test', string => 'this is a string', id => 1 });

for my $href(@array) {
    for my $sorted (sort_this('asc', $href)) {
        do_something($sorted, $href->{$sorted});
    }
    #This map could replace the for loop above; be warned about $_ in nested
loops
    #map { do_something($_, $href->{$_}); } sort_this('asc', $href);
}

sub sort_this {
    my ($direction, $href) = @_;
    if ($direction eq 'desc') {
        return reverse sort {$href->{$a} cmp $href->{$b}} keys %$href;
    } elsif ($direction eq 'asc') {
        return sort {$href->{$a} cmp $href->{$b}} keys %$href;
    } else {
        die "A horrible death, or just use Params::Validate\n";
    }
}

sub do_something {
    my ($key, $val) = @_;
    print "key: $key \t val: $val\n";·
}

#####################################

Chuck
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.pm.org/pipermail/victoria-pm/attachments/20071010/ab5fff12/attachment.html 


More information about the Victoria-pm mailing list