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

Hello all, I have a perl script that simply creates a db file. And then another that reads it. I have no problem in creating, but when I want to read the hash, the first key is retrieved fine; but the second key can't. please help. db looks like this: {TERM , DOCUMENT_NUMBER} -> VALUE The problem is that TERM is shown but the next key which is DOCUMENT_NUMBER is not correct (always returns 0). Thanks, Reza

-------------- create.pl -------------- #!/usr/bin/perl use GDBM_File; use Fcntl; open( myfile, "term_doc_freq.out" ) or die; my $lineNo; my %wordInDoc = (); tie (%wordInDoc, GDBM_File, "TermFreqDocid.db", O_CREAT|O_RDWR, 0644) +|| die ("Cannot create or open phone.db"); while( <myfile> ) { my($line) = $_; chomp $line; $lineNo++; @document = split (/ /, $line); $docID = $lineNo; foreach $term (@document) { $wordInDoc{$term}{$docID}=0; } foreach $term (@document) { ++$wordInDoc{$term}{$docID}; } } untie (%wordInDoc); exit; -------------- read.pl -------------- #!/usr/bin/perl use GDBM_File; use Fcntl; tie (%TermDocFreqHash, GDBM_File, "TermFreqDocid.db", O_RDONLY, 0777) +|| die ("Cannot open TermFreqDocid.db"); foreach $term ( sort( keys %TermDocFreqHash ) ) { print $term." "; my %tmp = $TermDocFreqHash{$term}; foreach $docID ( keys %tmp ) { print $TermDocFreqHash{$term}{$docID}; } } untie (%TermDocFreqHash); exit;

Replies are listed 'Best First'.
Re: Problem: read a GDBM hash with 2 keys in perl
by Corion (Patriarch) on Jun 29, 2010 at 17:15 UTC

    Does the GNU dbm library allow you to store complex structures? I would assume it only allows you to store plain strings, like most of the dbms except DBM::Deep do.

      When I print the results in create.pl, it is ok and it seams GDBM allows multidimensional hashtables. But as I said, when opening the .db file, it messes up. What should I to sort this out? Thanks, Reza
        and it seams GDBM allows multidimensional hashtables

        GDBM_File does definitely not allow multidimensional structures (just checked the sources).  Unless you serialize them, that is. See Storable, for example.