Home Ask Login Register

Developers Planet

Your answer is one click away!

Slufgest February 2016

Trouble recalling hashes from file in Perl

This phone book script works well in memory but I am having a difficult time recalling the saved data on re execution. The hashes go to the text file but I have no idea how to recall them when the script is starting. I have used "Storage" to save the data, and I have tried to use the "retrieve"function to bring the data back, with no luck. I think either I did not follow a good path from the start or I just don't know where in the code or which %hash should "retrieve" the stored data.

I am very new to Perl and programming so I hope I explained my situation clearly

#!/usr/bin/perl

use 5.18.2;
use strict;
use warnings;
use autodie;
use Scalar::Util qw(looks_like_number); # This is used to determine if the phone number entered is valid.
use Storable;
use Data::Dumper;

####################################
# Enables sub selections
my %contact; while (){
    my $selection = list();

    if ($selection == 1){
        addContact();
    }
    elsif ($selection == 2){
        removeContact();
    }
    elsif ($selection == 3){
                findContact();
    }
    elsif ($selection == 4){
        listAllContacts();
    }
    elsif ($selection == 5) {
                clearScreen();
        }
    elsif ($selection == 888) {
        quit();
    }
    else {
        print "Invalid entry, Please try again.\n\n"; # displays error message
    }
}
####################################
# Shows instructions for use
sub list{
    print "\n------------------------------------------------------------------------\n";
    print "-                     ----- Select an option -----                     -\n"; 
    print "- 1 = add, 2 = remove, 3 = find, 4 = list, 5 = tidy screen, 888 = quit -\n";
    print "------------------------------------------------------------------------\n";
    print "What would you like to do? ";
    my $listChoice = <STDIN>; # enter sub choice here
    return $listChoice;
}

####################################
# Add contact info s        

Answers


Grrrr February 2016

The store function comes from the module Storable (you can see full documentation for the module by typing perldoc Storable).

It's counterpart is called retrieve.

So in order to read back the contacts on the script start you can replace the line

my %contact; while (){

with

my %contact;
eval {
    %contact = %{ retrieve "pb.txt" };
};
while (1) {

The eval makes the retrieval not die on error (whether because pb.txt is not there or does not contain the data in a format compatible with Storable). You might want to have somewhat more elaborate error handling instead of just ignoring any errors, but this should do as an example.

Post Status

Asked in February 2016
Viewed 3,570 times
Voted 11
Answered 1 times

Search




Leave an answer


Quote of the day: live life