kiz has asked for the wisdom of the Perl Monks concerning the following question:

I have a complex data structure, an example of which can be created using the following code:
use Data::Dumper; my $free_table = {}; my $mastertitle = "title"; my $elementid = "foo"; my @unique_terms = qw(These guides were given a plug a few months ago +before the JISC conference in fact, where they were displayed and I f +orget to pick them up. However, I rectified that oversight on Friday +at that aforementioned news working group in the JISC offices in cent +ral London.); foreach my $index_term (@unique_terms) { # we have a three-level checking process to deal with # The word itself $free_table->{$index_term} = {} unless exists $free_table->{$index_term}; print "term = $index_term\n"; # The specific institution subdivision $free_table->{$index_term}->{$mastertitle} = {} unless exists $free_table->{$index_term}->{$mastertitle}; print "mastertitle = $mastertitle\n"; # "Archdesc" isad or "fond" isad # make a reference to the anonymous hash at this bottom level $data_type = int (rand 2) + 1; # Add the element to the bottom level $free_table->{$index_term}->{$mastertitle}->{$data_type} = {} unless exists $free_table->{$index_term}->{$mastertitle}->{$data_type}; $free_table->{$index_term}->{$mastertitle}->{$data_type}->{$elementi +d} = 1; } print( Dumper ( %{$free_table} ) );
Now - this is fine, and everything works as expected. If I now try to extend the concept so that the data structure is help on disk, I'd do something akin to:
unless ( -r "$repository_root/free/freetext.mldbm" ) { %free_table = (); } tie %free_table, 'MLDBM', "$repository_root/free/freetext.mldbm", O_CREAT | O_RDWR, 0640 or die $!; $free_table = \%free_table; &build_data_structure_as_above(@some_params); print( Dumper ( %free_table} );
However this only gives me a %free_table as an empty hash. If I change my code so that I'm not writing to a tied hash, things are different:
unless ( -r "$repository_root/free/freetext.mldbm" ) { %free_table = (); } tie %free_table, 'MLDBM', "$repository_root/free/freetext.mldbm", O_CREAT | O_RDWR, 0640 or die $!; $free_table = {}; &build_data_structure_as_above(@some_params); %free_table = %{$free_table} print( Dumper ( %free_table} );
This works.. The question is ... why?


-- Ian Stuart
A man depriving some poor village, somewhere, of a first-class idiot.

Replies are listed 'Best First'.
Re: Why can't I use a hash-ref to a tied hash?
by davido (Cardinal) on Jun 25, 2004 at 16:05 UTC

    Your reference is named $free_table, and it's referring to an anonymous hash.

    You are tieing a named hash, called %free_table.

    %free_table is not the same hash as %{$free_table}. That's your problem.


    Dave