Deleting Values
Deleting values is
the final operation that can be performed on DBM files. Updating is
as simple as assigning different values to the appropriate key within
the database, and deleting is equally simple. This operation is
performed by using the standard Perl
delete
function on the appropriate key
within the database. delete
removes it from the
hash that represents the database, and because the hash has been tied
to the DBM file, it is purged from that also.
The following program inserts three records into a Berkeley DB, and then dumps the database to show that the records are there. Following that process, a single record is deleted and the database is redumped to illustrate the deletion. Here’s the program:
#!/usr/bin/perl -w # # ch02/DBM/delete: Creates a Berkeley DB, inserts some test data then # deletes some of it use strict; use DB_File; ### Initialize the Berkeley DB my %database; tie %database, 'DB_File', "delete.dat" or die "Can't initialize database: $!\n"; ### Insert some data rows $database{'Callanish I'} = "Western Isles"; $database{'Avebury'} = "Wiltshire"; $database{'Lundin Links'} = "Fife"; ### Dump the database print "Dumping the entire database...\n"; foreach my $key ( keys %database ) { printf "%15s - %s\n", $key, $database{$key}; } print "\n"; ### Delete a row delete $database{'Avebury'}; ### Re-dump the database print "Dumping the database after deletions...\n"; foreach my $key ( keys %database ) { printf "%15s - %s\n", $key, $database{$key}; ...
Get Programming the Perl DBI now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.