Find Customers using a HASH
- customer
- This program loads a three element text file into two hashes and then
allows you to look for the keys Phone number or Email address in the hashes to view the customer
data orginally in the text file
customer
#! /usr/bin/perl -w
# Program to read a file "customers.txt" with three elements
# (name, phone, email)and place it into two hashes (%Phone, %Email).
# Then it ask for a phone number. If a number is entered the customer
# information will be printed. If no number is entered it will then ask
# for an email address. If "q" is entered for either the number or the
# address the program will quit.
# open the file
open (PH, "customers.txt") or die "Cannot open customers.txt: $!\n";
# place data into the two hashes
while (defined ($data = )) { # While data
chomp $data;
# Look for one or more word characters (\s+). Three will
# be found [0,1,2]. $number will become [1] and $email
# will become [2].
($number, $email) = (split (/\s+/,$data) )[1,2];
# $number becomes the key for %Phone
$Phone{$number} = $data;
# $email becomes the key for %Email
$Email{$email} = $data;
}
close (PH); # Close the file
print "Type 'q' to exit\n";
while (1) { # While true
print "\nNumber? ";
$number = ; chomp($number); # Get the number key
$address = "";
if (! $number) { # If no number get the email key
print "E-Mail? ";
$address = ; chomp ($address);
}
next if (! $number and ! $address); # If no number or address
last if ($number eq 'q' or $address eq 'q'); # If either is "q"
if ($number and exists $Phone{$number} ) { # If number use %Phone
print "Customer: $Phone{$number}\n";
next;
}
if ($address and exists $Email{$address} ) { # If addresse use %Email
print "Customer: $Email{$address}\n";
next;
}
print "Customer record not found. \n"; # Number or address not found
next;
}
print "\nAll done.\n"; # "q" was entered