Deleting Data

The final form of data manipulation that you can apply to flat-file databases is the removal, or deletion, of records from the database. We shall process the file a record at a time by passing the data through a temporary file, just as we did for updating, rather than slurping all the data into memory and dumping it at the end.

With this technique, the action of removing a record from the database is more an act of omission than any actual deletion. Each record is read in from the file, tested, and written out to the file. When the record to be deleted is encountered, it is simply not written to the temporary file. This effectively removes all trace of it from the database, albeit in a rather unsophisticated way.

The following program can be used to remove the relevant record from the delimited megalithic database when given an argument of the name of the site to delete:

#!/usr/bin/perl -w # # ch02/deletemegadata/deletemegadata: Deletes the record for the given # megalithic site. Uses # colon-separated data # ### Check the user has supplied an argument to scan for ### 1) The name of the file containing the data ### 2) The name of the site to delete die "Usage: deletemegadata <data file> <site name>\n" unless @ARGV == 2; my $megalithFile = $ARGV[0]; my $siteName = $ARGV[1]; my $tempFile = "tmp.$$"; ### Open the data file for reading, and die upon failure open MEGADATA, "<$megalithFile" or die "Can't open $megalithFile: $!\n"; ### Open the temporary megalith data file ...

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.