CGI Programming OpenFAQ


How do I use a simple text file database to dynamically populate entries in a form popup?

Contributors:

Suppose you have a tab delimited text database with records as lines. You can fill up your hash/array as follows (assuming column 1 are your keys, and column 3 are your labels that you want to appear in the form):

open(TDB,"text.db")
while () {
  @Fld = split(/\t/,$_, 9999);
  $vars{$Fld[0]} = $Fld[2];
}
close(TDB);

There are lots of other ways to populate a hash from a file, this is a simple one.

Then, assuming you use CGI.pm, you use the hash to fill the popup (or scrolldown, or checkboxes) like this (if you want entries sorted by the key $vars):

popup_menu(-name=>'what you want',
               -values=>[ sort keys %vars ],
               -labels=>\%vars,
               ),
This allows the menu items to be completely separate from the script. Note that this example assumes you are using the highly useful CGI.pm library, which is included with Perl 5.004 or later. It is also available through CPAN.

Previous | Next | Table of Contents