SPUG: Sorting hash question

Pommert, Daniel Daniel.Pommert at verizonwireless.com
Tue Apr 30 14:26:03 CDT 2002


It seems that your simplest solution would be to change your {[child #]} to
be an array reference from a hash reference.  The only reason why you
wouldn't want to do this (that I can think of) is that your subscripts are
very sparce (i.e. lots of gaps in the numbers).  If they are dense (i.e. no
gaps), then you should change your array to:
	$Item{Children}[child #]{other stuff}

With your examples becoming:
	$Item{Children}[1]{name}
	$Item{Children}[1]{content}
	$Item{Children}[2]{name}
	$Item{Children}[2]{content}

Get the Children of Item using:
	for $SubItem (@{$Item{Children}}) {
		next unless defined $SubItem;	# Handle [0] element
which gives you an ordered list.

Your second loop becomes:
	for $SubItem (@{$Item{Children}}) {
		next unless defined $SubItem;	# Handle [0] element
		. . .
	}

I hope this helps.

-- Daniel Pommert 
  Verizon Wireless
  425-603-8612

-----Original Message-----
From: Peter Darley [mailto:pdarley at kinesis-cem.com]
Sent: Tuesday, April 30, 2002 11:25 AM
To: SPUG
Subject: SPUG: Sorting hash question


Friends,
	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}})

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

	I would be greatfull for any suggestion! :)
Thanks,
Peter Darley


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

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