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

Hi,all great monks,I need your wisdom to help me.

I created a hash in SDBM_File.And one of its value is reference(ARRAY,HASH,whatever).It's failed when I dereference it to its original values,perl tell me it's undef.I researched it,then I found when I give a reference to a hash key,the hash just write the literal mem address into SDBM_File(e.g. 'ARRAY(0x123456)').when I read this key's value, it just give me the literal address string,and tell me it's not a ref.

use Fcntl; use SDBM_File; tie(%h,'SDBM_File','foodbm',O_RDWR|O_CREAT,0640) || die $!; $h{'a'}=1; %h{'b'}=[2,3]; if (ref $h{'b'}) { print "it's a ref,ok\n"; # perl will not print this! } else { print "it's not a ref,just $h{'b'}\n"; # this is what perl printed! } if (!defined $h{'b'}->[0]) { print "\$h{'b'}->[0] not defined!\n"; # perl also print this! } untie(%h);
Please tell me how can I store array ref or hash ref into SDBM_File and restore it to its original values. Thank you!

Replies are listed 'Best First'.
Re: hash in SDBM_File
by rob_au (Abbot) on Feb 24, 2002 at 08:50 UTC
    The best way to store data structures such as these intact is to serialise them prior to storage - There are a number of ways by which this can be performed but one of the fastest and most widely employed is through the Storable module. This module allows complex data structures to be broken down to storable and retrieveable serial strings via the freeze method, which can subsequently stored in files and then restored to the original data structure via the thaw method. eg.

    use Storable qw/ freeze thaw /; # Create serial representation of hash structure $serialised = freeze \%hash; . . . # Recreate hash structure from serial representation %hash = %{ thaw( $serialised ) }

    Other modules which allow the representation and storable of complex data structures within serial formats include Data::Dumper and Data::Denter - The primary advantage which Storable offers over these modules is speed.

     

    perl -e 's&&rob@cowsnet.com.au&&&split/[@.]/&&s&.com.&_&&&print'

Re (tilly) 1: hash in SDBM_File
by tilly (Archbishop) on Feb 24, 2002 at 09:06 UTC
    To add to the previous responses, you can simplify your interaction with the needed serialization process through MLDBM.
Re: hash in SDBM_File
by dws (Chancellor) on Feb 24, 2002 at 09:00 UTC
    SDBM_File stores string values for string keys. To get hash in and then retrieve it, you'll need to serialize the hash. Data::Dumper is one way to serialize/deserialize.