Database files as Hashes!!!

Very Easy: connect an external data file to a hash.

Program 1 - create the database add some records:

#!/usr/bin/perl

use strict;
my %DB;


dbmopen(%DB, 'my_data', 0755);

$DB{smith}="joe";
$DB{davis}="harry";

dbmclose(%DB);


Program 2 - open an existing database, print it out, add records
#!/usr/bin/perl

use strict;
my %DB;
my $key;

dbmopen(%DB, 'my_data', 0755) || die "DIES";


foreach $key (keys %DB)
{
    print "Key $key  Value  $DB{$key}\n";
}


$DB{jones}="sue";
$DB{edwards}="karen";

dbmclose(%DB);


Program 3 - create something more elaborate: multiple fields:

use strict;
my %DB;
my $data;

# we create a dataebase that looks like the following:
#    EID        firstName    lastName    amountDue    ZipCode
#   12543      shane          harris          23.56            48197
#   34512      adam          jones           56.77            48104   
#   66331      emily         davis           123.77           48971
#   22334      ryan           smith           98.56            84361

dbmopen(%DB, 'studentData', 0755);

# EID will be the key for the hash. we need to use the
# pack function to combine everything else

# we add shane
$data=pack("a20 a20 d a5","shane","coleman",23.56,"48197");
$DB{12543}=$data;

#we add adam
$data=pack("a20 a20 d a5","adam","jones",56.77,"48104");
$DB{34512}=$data;

#we add emily
$data=pack("a20 a20 d a5","emily","davis",123.77,"48971");
$DB{66331}=$data;

#we add ryan
$data=pack("a20 a20 d a5","ryan","smith",98.56,"84361");
$DB{22334}=$data;

dbmclose(%DB);

Program 4 - read the database created by Program 3

#!/usr/bin/perl
use strict;
my %DB;
my $data;
my ($fname,$lname,$amount,$zip);
my $key;


dbmopen(%DB, 'studentData', 0755);
foreach $key(sort (keys %DB))
{
    ($fname,$lname,$amount,$zip)=unpack("a20,a20 d a5",$DB{$key});
    print "$key  $fname  $lname  $amount  $zip\n";
}

dbmclose(%DB);


Some references for pack/unpack:

Tutorial from perl monks
Cheat sheet for all format codes