Is there a new challenge or has everyone just become bored? Anyway, here is my submission (run it from wherever; it will put the SQLite database in your home directory).
BE SURE TO INSTALL DBI AND DBD::SQLite VIA CPAN!
challenge.pl:
Code:
#!/usr/bin/perl
use diagnostics;
use DBI;
sub ask_command()
{
print "(store/get/exit/new):\t";
$response=<STDIN>;
chomp($response);
$response;
}
sub is_new()
{
$dbh->do("CREATE TABLE people (name, age);");
}
sub store_entry()
{
print "NAME:\t";
chomp($name=<STDIN>);
print "AGE:\t";
chomp($age=<STDIN>);
$dbh->do("INSERT INTO people VALUES ('$name',$age)");
}
sub get_entry()
{
print "(name/age/all):\t";
chomp ($name_age=<STDIN>);
if ($name_age eq 'name')
{
print "NAME:\t";
chomp($name=<STDIN>);
my $all=$dbh->selectall_arrayref("SELECT age FROM people WHERE name = '$name'");
foreach my $row (@$all)
{
($age)=@$row;
print "AGE:\t$age\n";
}
}
if ($name_age eq 'age')
{
print "AGE:\t";
chomp($age=<STDIN>);
my $all=$dbh->selectall_arrayref("SELECT name FROM people WHERE age = $age");
foreach my $row (@$all)
{
($name)=@$row;
print "NAME:\t$name\n";
}
}
if ($name_age eq 'all')
{
my $all=$dbh->selectall_arrayref("SELECT name, age FROM people");
foreach my $row (@$all)
{
($name,$age)=@$row;
print "NAME:\t$name\nAGE:\t$age\n";
}
}
}
$dbh=DBI->connect("dbi:SQLite:dbname=/home/$ENV{LOGNAME}/names.sqlt","","", { RaiseError => 1, AutoCommit => 1});
print "\n\tWelcome to Challenge7! If you have not yet created your names and ages table, enter 'new' in the following prompt to do so. Otherwise, select 'store' to store rows, 'get' to retrieve all rows or filter by name or age, and 'exit' to leave this program. Your empty database (without the necessary table) has already be created if it did not already exist in '/home/$ENV{LOGNAME}/names.sqlt' Enjoy, and please have the courtesy to file a bug report if you find a bug.\n\n";
$command=&ask_command;
while ($command ne 'exit')
{
if ($command eq 'new')
{
is_new();
} else
{
if ($command eq 'store')
{
store_entry();
} else
{
if ($command eq 'get')
{
get_entry();
}
}
}
$command=&ask_command;
}
Bookmarks