3 # under the terms of the GPL version 2, or any later version, at your
4 # option. See the file README and COPYING for more information.
5 # Copyright 2009 by Don Armstrong <don@donarmstrong.com>.
6 # $Id: perl_script 1432 2009-04-21 02:42:41Z don $
17 db-hash - create a database and query using it
21 db-hash [options] dbname key
22 db-hash --create [options] dbname < key_value.txt
25 --create, -c create dbname
26 --update, -u update dbname, create if it doesn't exist
27 --dump, -D dump dbname
28 --missing-newline, -n output a newline for unhashed keys
29 --include-key, -k output the key as well as the value
30 --debug, -d debugging level (Default 0)
31 --help, -h display this help
32 --man, -m display manual
44 Update a database; replaces all keys with the values loaded from the
45 file, but keeps existing keys which were not replaced
49 Dump database to stdout
51 =item B<--include-key,-k>
53 Output the key as well as the value. (Off by default)
55 =item B<--missing-newline,-n>
57 If a key doesn't exist in the database, output a newline. (Forced on
58 when --include-key set)
62 Debug verbosity. (Default 0)
66 Display brief usage information.
79 use Fcntl qw/O_RDWR O_RDONLY O_CREAT O_TRUNC/;
80 use MLDBM qw(DB_File Storable);
84 my %options = (debug => 0,
95 'create|c','update|u',
97 'include_key|include-key|k!',
98 'missing_newline|missing-newline|n!',
99 'debug|d+','help|h|?','man|m');
101 pod2usage() if $options{help};
102 pod2usage({verbose=>2}) if $options{man};
104 $DEBUG = $options{debug};
108 # push @USAGE_ERRORS,"You must pass something";
111 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
115 my ($db,@keys) = @ARGV;
119 if (not ($options{create} or $options{update})) {
120 tie %t_db, MLDBM => $db, O_RDONLY or
121 die "Unable to open $db for reading: $!";
124 tie %t_db, MLDBM => $db, O_RDWR|O_CREAT|($options{update}?0:O_TRUNC), 0666 or
125 die "Unable to open $db for writing: $!";
128 if (not defined $options{include_key}) {
129 $options{include_key} = $options{dump} ? 0 : 1;
133 if ($options{update}) {
137 my ($key,@val) = split /\t/;
138 $fast_db{$key} = [make_list($fast_db{$key} // [],@val)];
140 for my $key (keys %fast_db) {
141 $t_db{$key} = $fast_db{$key};
144 elsif ($options{create}) {
148 my ($key,@val) = split /\t/;
149 $fast_db{$key} = [make_list($fast_db{$key} // [],@val)];
151 for my $key (keys %fast_db) {
152 $t_db{$key} = $fast_db{$key};
155 elsif ($options{dump}) {
156 for my $key (keys %t_db) {
157 print "$key:".join("\t",make_list($t_db{$key}))."\n";
162 output_keys(<STDIN>);
171 for my $key (@temp) {
172 if (not exists $t_db{$key}) {
175 if ($options{include_key}) {
178 if (exists $t_db{$key}) {
179 print join("\t",make_list($t_db{$key}));
182 elsif ($options{missing_newline}) {
189 return map {(ref($_) eq 'ARRAY')?@{$_}:$_} @_;