#!/usr/bin/perl -w use strict; use Fcntl qw(:DEFAULT :flock); use Storable qw(store_fd fd_retrieve); use Data::Dumper; $Data::Dumper::Deepcopy=1; $Data::Dumper::Purity=1; $Data::Dumper::Sortkeys=1; sub db_load { my $fh = $_[0]; return fd_retrieve($fh); } sub db_save { my ($fh, $db_hashref) = @_; store_fd($db_hashref, $fh); return $fh; } sub fileopenandlock { my ($fh, $file) = @_; sysopen($fh, $file, O_RDWR|O_CREAT, 0777) or die("I can't open the filehandle $fh for file $file in order to +lock it\n"); flock($fh, LOCK_EX) or die("I can't get an exclusive lock LOCK_EX on the file handle $f +h\n"); return $fh; } sub filecloseandunlock { my $fh = $_[0]; flock($fh, LOCK_UN) or croak("I can't unlock LOCK_UN the file handle $fh\n"); close($fh) or croak("I can't close the filehandle $fh\n"); return 1; } my %data = ( 1 => 'FEE', 2 => 'FYE', 3 => 'FOH', 4 => 'FUM', ); my $db_file = "./giant.db"; # open and read db my $db_fh = do { local *DB }; my $db = db_load(fileopenandlock($db_fh,$db_file)); print "First read dump:\n"; print Dumper($db) . "\n\n"; # should dump empty # fill it up with data $db->{$_} = $data{$_} for sort keys %data; print "Dump before write:\n"; print Dumper($db) . "\n\n"; # should dump full # save db filecloseandunlock(db_save($db_fh,$db)); # test read - did it work? my $db_fhnew = do { local *DBNEW }; my $dbnew = db_load(fileopenandlock($db_fhnew,$db_file)); print "Second read dump:\n"; print Dumper($dbnew) . "\n\n"; # should dump full filecloseandunlock($dbnew);
In reply to Storable and passed filehandles by blahblah
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |