SPUG: Sorting hash question

Matt Tucker tuck at whistlingfish.net
Tue Apr 30 15:11:16 CDT 2002

-- Peter Darley <pdarley at kinesis-cem.com> spake thusly:

> 	I currently have a hash that looks like
> 		$Item{Children}{[child #]}{other stuff}
> 	A couple of examples would be:
> 		$Item{Children}{1}{name}
> 		$Item{Children}{1}{content}
> 		$Item{Children}{2}{name}
> 		$Item{Children}{2}{content}
> 	I'm getting at the Children of Item using:
> 		for $SubItem (values %{$$Item{Children}})

Why are you dereferencing it like this? %{$Item{Children}} is
sufficient. Additionally, if you're using numbers, why not just use an
array? Something like:


Unless, of course, the numbering is more sparse than the example you
give, in which case hashes probably make sense.

> 	which gives me an unsorted list of items.  I would like to have it
> sorted in the order of the keys of the %{$Item{Children}}.  I found
> lots of info on how to step through the keys of a hash sorted by
> value, but not anything on stepping through the values of a has
> sorted by key.  Is this easily doable, or should I do something like:
> 	for $SubItem (sort {$a<=>$b} keys %{$$Item{Children}})
> 	{
> 		$SubItem = $$Item{Children}{$SubItem};
> 		...
> 	}

This is a perfectly reasonable way to do it, although I would suggest
not repurposing the $SubItem variable. A better snippet would be:

	for my $subkey (sort {$a<=>$b} keys %{$Item{Children}})
		my $subItem = $Item{Children}{$subkey};
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://mail.pm.org/archives/spug-list/attachments/20020430/de8a64d8/attachment.bin

More information about the spug-list mailing list