in reply to Re: Weirdness when reading from DBM file
in thread Weirdness when reading from DBM file

Just wanted to report back on my results, which were phenomenal! This script writes the MySQL database to the DBM file:
#!/usr/bin/perl -w use strict; use Mojo::DB; use DBM::Deep; $| = 1; my $dbh = get_dbh(); die "No filename argument provided" unless @ARGV; my $file = shift @ARGV; unlink $file; # This is the magic. :-) my $db = DBM::Deep->new( $file ); tie my %IDS, 'DBM::Deep', $file or die "$!"; my @keys = qw(employee_id firstname lastname title dept salary date_hi +red); my $keys = join(', ', @keys); my $query = "select $keys from employee_data"; my @values = @{$dbh->selectall_arrayref($query)}; for my $v (@values){ my @vals = @$v; # one ID per array for (@vals){ $_ = '-' unless $_; } $db->{$vals[0]} = { (map { $keys[$_] => $vals[$_]; } 0 .. $#keys) }; }
and this script reads the data back out:
#!/usr/bin/perl -w use strict; use DBM::Deep; $| = 1; die "No filename argument provided" unless @ARGV; my $file = shift @ARGV; tie my %IDS, 'DBM::Deep', $file or die "$!"; while (my($k, $v) = each %IDS){ print "\n$k :\n"; while (my ($k, $v) = each %{$v}){ print "$k => $v\n"; } }
It really works like a dream, thank you so much. The nice thing, too, is that I almost understand how it works! I'm even going to leave your comment about "this is the magic" in there to remind me. : )


Any technology sufficiently advanced is indistinguishable from a Perl script.

Replies are listed 'Best First'.
Re^3: Weirdness when reading from DBM file
by dragonchild (Archbishop) on Sep 12, 2007 at 13:27 UTC
    *smiles* I'm glad it worked out for you. If you run into any problems with DBM::Deep, please let me know.

    As for map, it's conceptually pretty simple. You're used to functions taking a single thing as an argument and returning a single thing as a result. Map takes an action and a list of things as arguments, does the action to each of the things in turn, and returns the list of actioned things as a result.

    In the code above, what I'm doing is taking a list of indices and inflating each one into a key-value pair. Then, I'm using the fact that a hash can be assigned a list of key-value pairs to create my hash. Does that help make more sense?


    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?