The value of one of the keys? If you don't know *which* key in
respective hash, this appears to be pretty tricky...
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
--
Of course I know _which_ key. Each hash has a key "date_tm", I want to
sort all the hashes in the array by their date_tm value which is in the
format: yyyymmdddhhmm.
Chris.
> Gunnar Hjalmarsson wrote:
> > Chris Mortimore wrote:
> >> I want to sort an AoH. Not each hash by its keys, but the array by
> >> the value of one of the keys in each hash.
> >
> > The value of one of the keys? If you don't know *which* key in
> > respective hash, this appears to be pretty tricky...
>
> Of course I know _which_ key. Each hash has a key "date_tm", I want
> to sort all the hashes in the array by their date_tm value which is in
> the format: yyyymmdddhhmm.
Don't you think it might have been constructive to mention this the
first time around?
Can you please give a fuller description of [a] what this data structure
really looks like -- a Data::Dumper dump would be good -- and [b] how
you want to rearrange the contents of this structure?
--
Chris Devers
I want to sort an AoH. Not each hash by its keys, but the array by the
value of one of the keys in each hash.
I know how to sort a simple array.
I know how to sort a hash by the keys.
Could someone kindly point me to the documentation on sorting arrays of
hashes?
Thank you!
Chris.
Hope this gives you some ideas...
#! /usr/local/bin/perl
@AoH=({office=>C,employees=>500},{office=>A, employees=>30});
$ndx=0;
foreach (@AoH){
print "$_->{office}, $ndx \n";
$IofH{$_->{office}} = $ndx++;
}
foreach (sort keys %IofH){
print "$_, $IofH{$_}\n";
%nH = %{$AoH[$IofH{$_}]};
print "Office $_ has employees $nH{employees}\n";
}
jwm
`perldoc -q sort`
Ex.
my @AoH = ...
my @sorted = sort { $a->{key} cmp $b->{key} } @AoH;
Aha, the keys have the same name.. Good! Then Randy's suggested code
should do.
As regards documentation, besides "perldoc -f sort", there is a FAQ
entry that is very much applicable to this problem: "How do I sort an
array by (anything)?"
I want to sort an AoH. Not each hash by its keys, but the array by the
value of one of the keys in each hash. I know how to sort a simple
array. I know how to sort a hash by the keys. Could someone kindly point
me to the documentation on sorting arrays of hashes?
Thank you!
Chris.
Hope this gives you some ideas...
#! /usr/local/bin/perl @AoH=({office=>C,employees=>500},{office=>A,
employees=>30}); $ndx=0; foreach (@AoH){
print "$_->{office}, $ndx \n";
$IofH{$_->{office}} = $ndx++;
}
foreach (sort keys %IofH){
print "$_, $IofH{$_}\n";
%nH = %{$AoH[$IofH{$_}]};
print "Office $_ has employees $nH{employees}\n";
}
jwm
Thank you John. How to build the index and relate it back to the
original array of hashes is exactly what I was trying to figure out!
Gratefully, Chris.