*sigh* I actually wrote quite a beautiful little flatfile database editor, but managed to delete it before uploading for testing.
If I want to delete an item from a flatfile database I use the 'splice' command, which can selectively remove elements in an array.
The syntax goes, splice ARRAY, OFFSET, LENGTH, REPLACE-LIST
For example:
splice(@array, 0, 1);
Would delete
1 element, from the 0th element onwards... i.e. the first element.
Similarly,
splice(@array, 3, 2);
Would delete elements 3 and 4 from the array @array.
So for a flatfile database, you could do something like this:
Code:
#!/usr/bin/perl
$db = "flatfile.db";
chomp ($line_to_delete = <STDIN>);
open (DB, "$db") || die "Couldn't open $db for reading: $!";
@lines = <DB>;
close DB;
splice (@lines, $line_to_delete - 1, 1);
# the -1 there is because the 4th element in a list is referenced
# by '3' etc.. don't ask me who thought it was a good idea to
# start arrays with 0, but we're stuck with it now..
# this clobbers the contents and replaces them with the updated
# @lines array
open (DB, ">$db") || die "Couldn't open $db for writing: $!";
print DB @lines;
close DB;
print "Done\n";
So, if The Patriot copy had a nasty accident with a video recorder, you could delete its entry in the DB like so:
Code:
#!/usr/bin/perl
chomp($title_to_delete = <STDIN>);
open (DB, "$db") || die "Couldn't open $db for reading: $!";
@lines = <DB>;
close DB;
for ($i = 0; $i <= $#lines; $i++) {
# this line is a neat little trick for getting the title from the db
# i'll explain it afterwards..
($title = $lines[$i]) =~ s/\|.*//;
if ($title eq $title_to_delete) {
splice (@lines, $i, 1);
}
}
open (DB, ">$db") || die "Couldn't open $db for writing: $!";
print DB @lines;
close DB;
print "Done\n";
This line:
($title = $lines[$i]) =~ s/\|.*//;
Means this:
Copy the contents of the current line into $title, then get rid of everything after and including the first pipe found in it.
And as for arranging the database in alphabetical order.. well there's a great module called Sort::Fields which will do it for you. You can read about it
here
You could use it like this:
Code:
#!/usr/bin/perl
open (DB, "$db") || die "Couldn't open $db for reading: $!";
@lines = <DB>;
close DB;
@lines = fieldsort '\|', [0], @lines;
open (DB, ">$db") || die "Couldn't open $db for writing: $!";
print DB @lines;
close DB;
print "Done\n";
Feel free to ask any questions...