SPUG: Sorting hash question

Peter Darley pdarley at kinesis-cem.com
Tue Apr 30 16:26:57 CDT 2002

	The variable $Item is actually a reference in a scalar, rather than a hash,
so I need to re-reference it to $$Item{Children} before dereferencing it to
%{$$Item{Children}}, if that makes any sense.  If I don't need to do this, I
would be ecstatic, but it has been the only way I could figure out to do it.
Any suggestions?

Peter Darley

-----Original Message-----
From: Matt Tucker [mailto:tuck at whistlingfish.net]
Sent: Tuesday, April 30, 2002 1:11 PM
To: Peter Darley
Subject: Re: SPUG: Sorting hash question

-- 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};

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