#!/usr/local/bin/perl # Jaime Prilusky, 2009 # adapted from DB_File perldoc use warnings ; use strict ; use DB_File ; our (%h, $k, $v) ; my $dbFile = "fruit"; # only if we want to start from scratch # unlink $dbFile ; createDatabase($dbFile); dumpDatabaseContent($dbFile); # show what we have deleteFromDatabase($dbFile,"apple"); dumpDatabaseContent($dbFile); # show what we have sub createDatabase { my($dbFile) = @_; print "create database '$dbFile' ...\n"; tie %h, "DB_File", $dbFile, O_RDWR|O_CREAT, 0666 or die "Cannot open file $dbFile: $!\n"; # Add a few key/value pairs to the file $h{"apple"} = "red" ; $h{"orange"} = "orange" ; $h{"banana"} = "yellow" ; $h{"tomato"} = "red" ; untie %h ; } sub dumpDatabaseContent { my($dbFile) = @_; print "database '$dbFile' contents ...\n"; tie %h, "DB_File", $dbFile, O_RDWR; while (($k, $v) = each %h) { print "\t$k -> $v\n" } untie %h ; } sub deleteFromDatabase { my($dbFile,$key) = @_; print "delete from database '$dbFile' key/value '$key' ...\n"; tie %h, "DB_File", $dbFile, O_RDWR; if (!$h{$key}) { print "unable to find key $key\n"; } else { delete $h{$key} ; } untie %h ; }