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

Hello fellow monks:
I've been learning how to use DBM and I've noticed some differences between tied and untied hashes. Before tying this code to the DBM, it worked fine, but afterwards, it spits out an error. Any ideas what I'm doing wrong?
#!/usr/bin/perl -w use strict; my %TEST; my @fileData; dbmopen(%TEST, "mydata", 0777) || die "couldn't open the dbm"; open(TEST, "test2.txt") || die "Could not open the file for reading: $ +!"; while (<TEST>) { chomp; my ($key,@fileData) = split /\|/; $TEST{$key} = \@fileData; } close(TEST); print "$TEST{matthew20}->[1]";

Replies are listed 'Best First'.
Re: Differences between normal hashes and DBM tied hashes
by petdance (Parson) on Jul 02, 2001 at 08:06 UTC
    You're storing a reference in your database, which is just the memory address of the list. That's not significant once you read it. What would it be pointing to?

    You need to store the data itself in the file:

    $TEST{$key} = join( "|", @filedata )
    then you'll be storing the actual data that you want.

    And of course, you could improve the efficiency a bit by not splitting, stripping and rejoining, like so:

    s/^([^|]+)|//; my $key = $1; $TEST{$key} = $_;
    You're finding the first sequence up to the pipe, and stripping it off, but you're then stashing what you stripped into $key.

    xoxo,
    Andy
    --
    Throw down the gun and tiara and come out of the float!

Re: Differences between normal hashes and DBM tied hashes
by davorg (Chancellor) on Jul 02, 2001 at 13:42 UTC

    For storing complex data in a DBM file, you might like to look at the MLDBM module from CPAN.

    The documentation for dbmopen says "This function has been superseded by the tie() function". I suggest you take a look at tie as it gives you more control and power over your tied objects.

    --
    <http://www.dave.org.uk>

    Perl Training in the UK <http://www.iterative-software.com>

Re: Differences between normal hashes and DBM tied hashes
by DBX (Pilgrim) on Jul 02, 2001 at 09:13 UTC
    Another great tool for storing complex data structures is Data::Dumper I highly recommend it, I think it will work well for what you are attempting above.
Re: Differences between normal hashes and DBM tied hashes
by mugwumpjism (Hermit) on Jul 02, 2001 at 14:48 UTC

    I suggest you try the Storable module for a method of converting complex data structures to/from a stream that doesn't use eval() to bring it back.