Search code examples
perldbm

Can I use a filehandle instead of a filename for creating DBM files?


I'm using MLDBM to persist some Perl data structures and I'm wondering if there's an alternative to the following:

tie %hash, "MLDBM", $dbm_file, O_CREAT | O_RDWR, 0644;

Primarily, I'd like to be able to use STDOUT, rather than a known file name. This could then be redirected to a file on the shell-side.

I've been searching with keywords like "tie", "DBM" and "filehandle", but the hits tend to talk about tying filehandles to things, as opposed to things to filehandles.

Any suggestions?


Solution

  • Well, MLDBM wouldn't care, as it just passes the parameters to the underlying dbm library (e.g., DB_File or GDBM_File). But I'm not aware of any dbm library that accepts a filehandle instead of a filename. Also, a dbm file will need to be seekable, so the shell would have to be redirecting to an actual file, not a pipe. And STDOUT would probably be opened write-only, which wouldn't work for a dbm file.

    If you're just using MLDBM for persistence, and not because the database is too big for memory, then you could try a different approach. Use Storable to persist your data structures. It can read & write to an already-open filehandle.