Can anyone provide a simple explanation as to how to do this so I can finish this chapter.
It used to be (Perl 4) that you could tie() a dbmfile to a hash, something on the order of
[perl]
tie my %hash, "foo.dbm" or die "$@";
foreach my $i (%hash) {
print "$i = " . $hash{$i} . "\n";
}
[/dbm]
I think that's been deprecated in favour of a module. Check CPAN for modules with DBM (i /dbm/) or see if there is something like DBM.pm on your system and then read the perldoc.
Sean
use strict;
use DB_File [perl.com];
my $file = 'file.dbm';
my %db;
tie(%db, 'DB_File', $file)
or die "Can't tie $file: $!";
while (my($k, $v) = each %db) {
print '$k = $v\n';
}
That is a very basic example. check out that link for some good info and different ways to use it.
[b]
use SDBM_File;
use Fcntl;
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
[/b]
[b]
sub save_to_dbase {
#declare variables
my %comments;
#open dbase, add record, close dbase
tie(%comments, "SDBM_File", "commentslist", O_CREAT¦O_RDWR, 0666)
or die "Error opening commentslist. $!, stopped";
$comments{email} = "$name¦$comments";
untie(%comments);
[/b]
Name: email
Comments:
sub create_comments_page{
#declare variables
my %commentslist;
my ($name, $comment, $rec);
#open db in a read only format
tie(%commentslist, "SDBM_File", "commentslist", O_RDONLY, 0666)
or die "Error opening commentslist. $!, stopped";
#print statements to web page
print "<HTML><HEAD><TITLE>International Coffees Responses</TITLE></HEAD>\n";
foreach my $rec (%commentslist){
chomp($rec);
($name,$comment) = split(/\¦/,$rec);
print "<B>Name:</B> $name<BR>\n";
print "<B>Comments:</B> $comment<BR>\n";
print "<HR>";
}
print "</BODY>\n";
print "</HTML>\n";
}#end create_comments_page
Try this instead:
while (my($key, $val) = each %commentslist){
($name,$comment) = split(/\¦/,$val);
print "<B>Name:</B> $name<BR>\n";
print "<B>Comments:</B> $comment<BR>\n";
print "<HR>";
}
I would actually change the first script in this way. The difference is, you are using the key to hold the name then just putting comment as value. You defeat the purpose by sticking them together with a pipe(¦) and then splitting them up later.
sub save_to_dbase {
#declare variables
my %comments;
#open dbase, add record, close dbase
tie(%comments, "SDBM_File", "commentslist", O_CREAT¦O_RDWR, 0666)
or die "Error opening commentslist. $!, stopped";
$comments{$name} = $comments;
untie(%comments);
while (my($name, $comment) = each %commentslist){
print "<B>Name:</B> $name<BR>\n";
print "<B>Comments:</B> $comment<BR>\n";
print "<HR>";
}