{
name => 'Bob Kowalski',
home_town => 'Vero Beach',
home_state => 'Florida',
hobbies => [ 'ham radio', 'Perl programming', 'running' ],
}
####
{
name => 'Kranessa Evans',
home_town => 'Dallas',
home_state => 'Texas',
hobbies => [ 'Perl programming', 'writing', 'polo' ],
}
####
#!/opt/perl
use strict;
use warnings;
my @students = (
{
name => 'Bob Kowalski',
home_town => 'Vero Beach',
home_state => 'Florida',
hobbies => [ 'ham radio', 'Perl programming', 'running' ],
},
{
name => 'Kranessa Evans',
home_town => 'Dallas',
home_state => 'Texas',
hobbies => [ 'Perl programming', 'writing', 'polo' ],
},
);
store_to_file( '/data/students.db', \@students ); # This make-believe easy-peasy function
# would be built into Perl.
####
use Storable qw( nstore_fd retrieve_fd );
sub store_to_file {
my ( $db, $data_ref ) = @_;
sysopen( DF, $db, O_RDWR | O_CREAT, 0606 )
or die "Can't open '$db', stopped: $!";
flock( DF, LOCK_EX )
or die
"Can't get exclusive lock on '$db' for writing, stopped: $!";
nstore_fd( $data_ref, *DF )
or die "Can't store data: $@";
truncate( DF, tell(DF) );
close(DF);
return 1;
}
sub retrieve_from_file { # Certainly going to need this complementary function in the future,
# to read my students' information.
my $db = shift;
unless ( -e $db ) {
store_to_file( [] ); # Initialize upon first-ever usage of this function if no student
# information has been stored before, so it won't crash in that instance
# because the data file doesn't exist yet. Maybe there's an easier,
# softer way to instantiate the data file in this admittedly unusual
# scenario (which I managed to encounter last night).
}
open( DF, "< $db" )
or die "Can't open '$db' for reading, stopped: $!";
flock( DF, LOCK_SH )
or die
"Can't get shared lock on '$db' for reading, stopped: $!";
my $data_ref = retrieve_fd(*DF);
close(DF);
return $data_ref;
}