Re: [Golf-ish] Ordered hash keys



* Damian James schrieb:
>
> So I wanted to define a lookup table that I would later need to
> iterate over in a specific order. That's easy enough, there are
> many ways to do it; but I specifically wanted to keep the neat,
> visually oriented table in my code:
>
> my @mappings = (
> field1 => 'otherLongwindedDirectoryAttribute',
> field2 => 'kitchenSink',
> field3 => 'userDistanceBetweenEyes'
> );
> my %lookup = @mappings;
> my @fields = @mappings[ map $_*2, 0..($#mappings/2) ];
>
> ...where obviously I am only interested in %lookup and @fields, but
> want to keep the table in the interests of easy alteration.

When typing `perldoc -q "keep my hash sorted"` I get:

Found in C:\Programme\Perl\lib\pod\perlfaq4.pod
How can I always keep my hash sorted?
You can look into using the DB_File module and tie() using the $DB_BTREE
hash bindings as documented in "In Memory Databases" in DB_File. The
Tie::IxHash module from CPAN might also be instructive.

Have a look at this Tie::IxHash from CPAN. Your code could look like:


use Tie::IxHash;
tie( my %lookup, 'Tie::IxHash',
field1 => 'otherLongwindedDirectoryAttribute',
field2 => 'kitchenSink',
field3 => 'userDistanceBetweenEyes'
);
my @fields = keys %lookup;


But I think you don't need your array @fields anymore when using this
module. When keep sorted your Hash by another value have a look at
Tie::Hash::Sorted. In the past many people have thought about ordered
hashes -- I think you won't reinventing the wheel ... ;-)

regards,
fabian
.



Relevant Pages

  • Re: compile time vs. run time?
    ... >> lookup table array would store a string and a function pointer. ... >> your code could just iterate over the array, ...
    (comp.lang.cpp)
  • [Golf-ish] Ordered hash keys
    ... So I wanted to define a lookup table that I would later need to ... iterate over in a specific order. ... or more elegant 'hashificator' that might be suitable in place of the ...
    (comp.lang.perl.misc)