http://qs321.pair.com?node_id=551218


in reply to Trouble with Tie::IxHash

You're not creating the nested hash in the proper order, as you're using anonymous hashes as values somewhere, which are intrinsically unordered. And then, it's too late to fix it.

First off, take a look at a module our co-monk japhy wrote: Tie::Autotie. It'll automatically tie deeper hashes also. If you then would assign the values one by one, it would already work:

use Tie::Autotie 'Tie::IxHash'; tie %hash_ref, 'Tie::IxHash'; # yuck, that variable's name! $hash_ref{MAIN}{ZOP}{Dev} = undef; $hash_ref{MAIN}{ZOP}{Con} = undef; ... # etc

You might not like the required syntax — though for reading from a data file, it'd probably work fine. I'm thinking of an alternative to anonymous hashes: tied hash references. I don't know if any module already implements them, but you can build them by hand:

sub ixhash { tie my(%hash), 'Tie::IxHash'; %hash = @_; return \%hash; }
In that case, you should be able to write (including the above sub):
use Tie::IxHash; tie %hash_ref, 'Tie::IxHash'; %hash_ref = ( 'MAIN' => ixhash( 'ZOP' => ixhash( 'Dev', undef, 'Con', undef, 'Test', undef, 'Exit', undef, 'New', undef ), 'AP' => ixhash( 'Dev', undef, 'Con', undef, 'Test', undef, 'Exit', undef, 'New', undef ), 'Exit' => undef, ) );
which looks acceptable to me... no?

update n.b. You don't need to use Tie::Autotie if you use the latter suggestion, make sure to replace every anonymous hash with a call to ixhash(), and never rely on autovivification.

p.s. You can use Tie::Hash::Indexed as a plug-in replacement for Tie::IxHash. The former is written in XS, the latter in Pure Perl, so it should be faster. I haven't run a benchmark, though.

Replies are listed 'Best First'.
Re^2: Trouble with Tie::IxHash
by Anonymous Monk on May 24, 2006 at 23:04 UTC

    I think your suggestion will perfectly suit my requirement but it seems that Autotie will only for perl version 5.8.3 or more. Unfortunately, I have only 5.6.1 and don't have authorization to update perl version in my system.

    Is there a workaround to use this somehow?

    Appreciate your help...