Re: how to efficiently sort hash without using keys()



On Wed, May 25, 2005 at 11:45:17AM +0200, Ing. Branislav Gerzo wrote:

> Hi beginners@xxxxxxxx,
>
> anyone has better idea how to sort hash by key without using keys()
> function? (I can't use it, it resets iterator...).
>
> my bruteforce looks:
>
> use strict;
> use warnings;
>
> my %hash = ( 1 => 'one',
> 2 => 'two',
> 3 => 'three'
> );
>
> my @array = ();
> while (my ($key, $value) = each(%hash)) {
> push @array, $key;
> }
> @array = sort @array;

Using each will also affect the iterator.

> but I think there should be better way. Anyone?
> I mean, snippet should do something like:
>
> for my $key (sort {$a <=> $b} keys %hash) {
> #do something $key
> }

I suggest changing the the previous code so it doesn't care what happens
to the iterator. For example:

my @keys = keys %hash;
for (@keys)
{
some_sub_that_messes_with_the_iterator();
}

--
Paul Johnson - paul@xxxxxxxx
http://www.pjcj.net
.