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 Reverse the database (value looks up keys instead); only useful during
67 Debug verbosity. (Default 0)
71 Display brief usage information.
84 use Fcntl qw/O_RDWR O_RDONLY O_CREAT O_TRUNC/;
85 use MLDBM qw(DB_File Storable);
89 my %options = (debug => 0,
100 GetOptions(\%options,
101 'create|c','update|u',
103 'include_key|include-key|k!',
105 'missing_newline|missing-newline|n!',
106 'debug|d+','help|h|?','man|m');
108 pod2usage() if $options{help};
109 pod2usage({verbose=>2}) if $options{man};
111 $DEBUG = $options{debug};
115 # push @USAGE_ERRORS,"You must pass something";
118 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
122 my ($db,@keys) = @ARGV;
126 if (not ($options{create} or $options{update})) {
127 tie %t_db, MLDBM => $db, O_RDONLY or
128 die "Unable to open $db for reading: $!";
131 tie %t_db, MLDBM => $db, O_RDWR|O_CREAT|($options{update}?0:O_TRUNC), 0666 or
132 die "Unable to open $db for writing: $!";
135 if (not defined $options{include_key}) {
136 $options{include_key} = $options{dump} ? 0 : 1;
140 if ($options{update} or $options{create}) {
144 my ($key,@val) = split /\t/;
145 if ($options{reverse}) {
146 for my $val_key (@val) {
147 $fast_db{$val_key} = [make_list($fast_db{$val_key})//[],$key];
151 $fast_db{$key} = [make_list($fast_db{$key} // [],@val)];
154 for my $key (keys %fast_db) {
155 $t_db{$key} = $fast_db{$key};
158 elsif ($options{dump}) {
159 for my $key (keys %t_db) {
160 print "$key\t".join("\t",make_list($t_db{$key}))."\n";
165 output_keys(<STDIN>);
174 for my $key (@temp) {
175 if (not exists $t_db{$key}) {
178 if ($options{include_key}) {
181 if (exists $t_db{$key}) {
182 print join("\t",make_list($t_db{$key}));
185 elsif ($options{missing_newline}) {
192 return map {(ref($_) eq 'ARRAY')?@{$_}:$_} @_;