in reply to Perl and Databases
#!/usr/bin/perl use Data::Dumper; #Use the Data::Dumper module use Fcntl ':flock'; #Need the flock module also &dbfile("open", "database"); #open database for reading & writing #You can do any data struture you want with hash %db $db{'hash'} = "hash_value"; push @{$db{'array'}}, "array_value"; &dbfile("close", "database"); #save and close database #If this is a CGI script, uncomment the following line: #print "Content-type: text/html\n\n"; &dbfile("open", "database"); print "Hey look at the value in \$db{'hash'}: $db{'hash'} \n"; print "And what's in \$db{'array'}[0]?: $db{'array'}[0]\n"; &dbfile("close", "database"); #Sub - opens/closes databases sub dbfile { if ($_[0] eq "open") { #open a database open LOCKFILE, ">>lock.lck" or die "Error! Could not lock database!"; flock LOCKFILE, LOCK_EX or die "Error! Could not lock database!"; do "$_[1].dat"; } if ($_[0] eq "close") { #save & close database $Data::Dumper::Purity = 1; $Data::Dumper::Indent = 0; open FILE, ">$_[1].dat"; print FILE Data::Dumper->Dump([\%db], ['*db']); close FILE; close LOCKFILE; %db = (); } #mmm... not opening database or closing. #What are you trying to do?! if ($_[0] ne "open" && $_[0] ne "close") { die "Error! Wrong parameter + passed to db_file()!"; } }
It is missing some stuff such as strict, making sure you don't open 2 databases, try to close a database that does not exist, or even making sure that you save to the same database that you opened (though this is not really a bug; it would allow you to copy a database), etc. But it gives you a general idea, so I figure it is a good enough of an example.
Also, here is the contents of file "database.dat" from my example. You'll notice I have taken out indentation to get rid of the extra space needed for all the spacing.:
%db = ('array' => ['array_value'],'hash' => 'hash_value');
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Perl and Databases
by lachoy (Parson) on Mar 29, 2002 at 13:37 UTC |