Perl Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 5.00

DBM Database Example - Book Records with Multiple Fields

This section provides a tutorial example of using DBM database files to build book records with multiple fields by joining them into a single string value.

This DBM example will show you how to manage a table with multiple columns. In the following Perl program, BookInsert.pl, I joined all columns into a single string with "\t" as the delimiter, and stored it into the hash:

#- DbmInsert.pl
#- Copyright (c) 1996 by Dr. Herong Yang, http://www.herongyang.com/
#
   ($name) = @ARGV;
   die "Missing DBM name.\n" unless $name;
   dbmopen(%map,$name,0666);
   $id = &lastKey();
   $id++;
   $key = $id;
   $title = "Programming Perl";
   $author = "Larry Wall";
   $date = "Jan 1991";
   $isbn = "0937175641";
   $edition = "1";
   $val = join("\t",$title,$author,$date,$edition,$isbn);
   $map{$key} = $val;
   $id++;
   $key = $id;
   $title = "Learning Perl";
   $author = " Randal L. Schwartz";
   $date = "Nov 1993";
   $isbn = "1565920422";
   $edition = "3";
   $val = join("\t",$title,$author,$date,$edition,$isbn);
   $map{$key} = $val;
   dbmclose(%map);
   exit;
sub lastKey {
   local $max = 0;
   local $key, $val;
   while (($key,$val)=each(%map)) {
      $max = $key if ($key>$max);
   }
   return $max;   
}

To bring back individual columns from the hash, I used the split function as shown in the following program, BookPrint.pl

#- BookPrint.pl
#- Copyright (c) 1996 by Dr. Herong Yang, http://www.herongyang.com/
#
   ($name) = @ARGV;
   die "Missing DBM name.\n" unless $name;
   dbmopen(%map,$name,0666);
   $rec = 0;
   while (($key,$val)=each(%map)) {
      $rec++;
      $id = $key;
      ($title,$author,$date,$edition,$isbn) = split("\t",$val);
      print "\nRecord: $rec\n";
      print "        id = $id\n";
      print "    author = $author\n";
      print "      date = $date\n";
      print "   edition = $edition\n";
      print "      isbn = $isbn\n";
   }
   dbmclose(%map);
   exit;

Here is the output of running these programs together:

>bookinsert.pl bookbase

>bookprint.pl bookbase

Record: 1
        id = 1
    author = Larry Wall
      date = Jan 1991
   edition = 1
      isbn = 0937175641

Record: 2
        id = 2
    author =  Randal L. Schwartz
      date = Nov 1993
   edition = 1
      isbn = 1565920422

Sections in This Chapter

dbmopen() - Opening DBM Files with Hash Variables

DBM Database Example - English French Dictionary

DBM Database Example - Book Records with Multiple Fields

Dr. Herong Yang, updated in 2008
DBM Database Example - Book Records with Multiple Fields