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

We have a software package that is creating GDBM files. I need to take a look at what's being created so I can parse the data out to users. Unfortunately, I've never worked with these before and my script keeps bombing. I'm reading through the Perl Cookbook and Programming Perl to no avail. Here's my script:
#!/usr/bin/perl -w use strict; use DB_File; my (%HASH, $key, $val); my $filename = "trans.gdbm"; tie (%HASH, "DB_File", $filename) or die "Can't open $filename: $!\n"; while (($key, $val) = each %HASH) { print "$key::$val\n"; } untie %HASH;
I keep getting the error message: Can't open trans.gdbm: File exists. Well, duh! I know the file exists. That's why I'm trying to read the darned thing! How the heck do I open these and read them? I took this code from the Cookbook, but obviously I've missed something.

Thanks in advance!

Cheers,
Ovid

Great. Just great. Now everyone's going to know this level 7 Monk is a fake :)

Replies are listed 'Best First'.
RE: GDBM files
by lhoward (Vicar) on Jul 25, 2000 at 03:03 UTC
    Your problem is that the default is for the tie DB_File call to create a new file. The following excerpt is taken from the DB_File docs:
    tie %A, "DB_File", "filename" ;
    is equivalent to:
    tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0666, $DB_HASH ;
    Try it without the implied O_CREAT argument:
    tie (%HASH, "DB_File", $filename, O_RDWR) or die "Can't open $filename +: $!\n";
      Thanks for the info. Now it gives the following very helpful error message:
      Can't open trans.gdbm:
      What's that? Is $! undef all of a sudden? Sigh. I'll keep pluggin' away.

      Nah, O_CREAT is just "Create the file if it doesn't exist." I'd say the real problem is that DB_File doesn't support GDBM files. :)

      Try GDBM_File instead. It's part of the default perl5 distribution (though it won't be installed unless you have the appropriate GDBM libraries and include files.)

      -Matt

RE: GDBM files
by steveAZ98 (Monk) on Jul 25, 2000 at 05:29 UTC
    This works for me
    tie %HASH, 'DB_File', 'trans.gdbm', O_RDWR, 0666, $DB_HASH or die "Can +'t open $filename: $!\n";
    As long as the file your trying to open is a Berkeley DB Hash file, otherwise I get the same error that you do. Try running file trans.gdbm and making sure it's the right type of file.
    HTH
Re: GDBM files
by davorg (Chancellor) on Jul 25, 2000 at 11:58 UTC