Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Maintain order of hash keys

Status
Not open for further replies.

Xaqte

IS-IT--Management
Oct 4, 2002
971
0
0
US
I was looking for a way to maintain the order of hash keys,
and the only solutions I could find where to either populate a "sort" keys of the position and sort by that, or use Tie::IxHash.

As most, I hate adding another module dependency unless necessary....

So, this is what I came up with:

Code:
sub iterator {
    my @index;
    my %hash;
    for my $i ( 0 .. ( scalar @_ ) - 1 ) {
        next if ($i % 2);
        $hash{$_[$i]} = $_[($i + 1)];
        push @index, $_[$i];
    }

    return sub {
        return () if !@index;
        my $key = shift(@index);
        if ( wantarray ) {
            return ($key, $hash{$key});
        }
        else {
            return $key;
        }
    }
}

my $i = iterator(
    one     =>  1,
    two     =>  2,
    three   =>  3
);

while ( my ($key, $value) = $i->() ) {
    print "$key => $value\n";
}

    ## O R ##

while ( my $k = $i->() ) {
    print "$k\n";
}

Hope you like it!
 
Or you could just use an array of hashes:

Code:
my $i = [
   {one=>1},
   {two=>2},
   {three=>3},
];
	
foreach my $j (@{$i}) {
   foreach my $key (keys %{$j}) {
      print "$key = $j->{$key}\n";
   }
}

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Arrays are lists, that is ordered collections where duplicates are permitted; hashes are collections indexed by keys with no possible duplicates of the key and powerful search capabilities( [tt]if(exists...[/tt] ).
So the two are not mixable: if you want to keep the order of creation, then you must allow for duplicates; if you want fast search and sorting, then you must abandon the ordering.
The only mixed solution that comes to mind (not very elegant) consists in modifying your keys at creation time like so
[tt] 001_one => 1,
002_two => 2,
003_three => 3, ...[/tt]
In this way the sort will output in the original order and it is easy to recover the original keys for display purposes; however you won't catch and suppress the duplicates, but if this is what you want...

Franco
: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
Good point about the possibility of introducing duplicate hash keys in an array of hashes.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top