SPUG: Sorting hash question
Damian Conway
damian at conway.org
Tue Apr 30 16:09:08 CDT 2002
Peter Darley wrote:
> I would like to have it [a multi-level hash] sorted
> in the order of the keys of the %{$Item{Children}}.
The others who have suggested an array at the thrid level are right, but seeing
that you have a morbid fear of mixed data structures (;-) here's a way to iterate
through a hash, but in a sorted order:
# walk through values of %hash in numeric order of its keys...
for $next ( @hash{sort {$a<=>$b} keys %hash} ) {
# do something with $next
}
This uses a hash slice, slicing on the pre-sorted the keys of the hash.
In your case that becomes:
for $SubItem (@{$Item{Children}}{sort {$a<=>$b} keys %{$Item{Children}}}) {
# do something with $SubItem
}
Frankly, you might want to reconsider the array-based solution ;-)
Damian
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
POST TO: spug-list at pm.org PROBLEMS: owner-spug-list at pm.org
Subscriptions; Email to majordomo at pm.org: ACTION LIST EMAIL
Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
For daily traffic, use spug-list for LIST ; for weekly, spug-list-digest
Seattle Perl Users Group (SPUG) Home Page: http://seattleperl.org
More information about the spug-list
mailing list