#!/usr/bin/perl -w use strict; use DB_File; use Getopt::Long; my $debug=0; my $convertfrom; my $convertto; my $printname=0; sub usage { die "$0 dbfile1 [dbfile2]: cats the files on stdout\n$0 --convertfrom [textfile|-] --convertto dbfile.db:\n converts the colon separated key/data file to newdb format\n"; } GetOptions("debug" => \$debug, "convertfrom=s" => \$convertfrom, "convertto=s" => \$convertto) or usage; if (defined $convertfrom and defined $convertto) { my $line; my $key; my $value; my %data; if ($convertfrom eq "-") { open (FROM, "<&STDIN") or die "Can't dupe STDIN: $!"; } else { open (FROM, $convertfrom) or die "Can't open convertfrom: $!"; } OpenCreateDB(\%data, $convertto); while ($line=) { chomp $line; next if ($line =~ /^\s*$/); next if ($line =~ /^#/); $line =~ /([^:]+):\s*(.+)/ or die "Can't split '$line' in key/value\n"; ($key, $value) = ($1, $2); print "Adding $key -> $value\n" if ($debug > 1); $data{$key}=$value; } CloseDB(\%data); } elsif ($#ARGV>-1) { $printname=1 if ($#ARGV>0); foreach (@ARGV) { my $key; my $val; my %data; if (! dbmopen(%data,$_,0444)) { if ($! eq "Invalid argument" or not $!) { print STDERR "Opening $_ in newdb format\n"; OpenReadDB(\%data, $_) } else { die "Can't open $_: $!"; } } else { print STDERR "Opening $_ in dbm format\n"; } while (($key,$val) = each %data) { if ($printname) { print "$_: $key -> $val\n"; } else { print "$key -> $val\n"; } } } } else { usage; } # Open a Btree DB file just for reading. sub OpenReadDB { my ($DB,$dbfilename,$type) = @_; $type=$DB_BTREE if (! $type); # $DB_HASH is another option tie (%$DB, 'DB_File', $dbfilename, O_RDONLY, 0, $DB_BTREE) or die "Can't tie $dbfilename: $!"; } # Open an _existing_ DB file for reading and writing sub OpenWriteDB { my ($DB,$dbfilename,$type) = @_; $type=$DB_BTREE if (! $type); # $DB_HASH is another option tie (%$DB, 'DB_File', $dbfilename, O_RDWR, 0, $DB_BTREE) or die "Can't tie $dbfilename: $!"; } # Creates a DB file for writing (note that this will fail if the file # already existed) sub OpenCreateDB { my ($DB,$dbfilename,$type) = @_; $type=$DB_BTREE if (! $type); # $DB_HASH is another option die "Can't create: $dbfilename already exists\n" if (-e $dbfilename); tie (%$DB, 'DB_File', $dbfilename, O_RDWR | O_CREAT | O_EXCL, 0664, $DB_BTREE) or die "Can't tie $dbfilename: $!"; } sub CloseDB { my ($DB) = @_; # We still use this function instead of calling untie directly so that # this function can be extended or changed in the future without # changing all the code that references it. untie %$DB; }