Find Customers using a HASH and matching
- customer
- This program is an expansion of the customer program. In addition to indexing
the file by the phone number and email address it allows indexing by the customers
last name.
customer2
#! /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 no email address it will ask for the customers
# last name. If "q" is entered for either the number, the
# address or the last name 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
while (1) { # While true (continous loop)
$number = "";
$address = "";
$lname = "";
print "\nType 'q' to exit\nNumber? ";
$number = ; chomp($number); # Get the number key
if (! $number) { # If no number get the email key
print "E-Mail? ";
$address = ; chomp ($address); # Get the email
if (! $address) {
print "Last name? ";
$lname =; chop ($lname); # Get the last name
}
}
next if (! $number and ! $address and ! $lname); # Repeat if no number, address or name
last if ($number eq 'q' or $address eq 'q' or $lname eq 'q'); # If any is "q" exit loop
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;
}
if ($lname) { # Was a last name entered
$cnt = 0;
print "Customer:\n";
foreach (keys %Phone) { # Check each record
$_ = $Phone{$_}; # Get the record
if (m/$lname\,/) {
$cnt = ++$cnt; # Counter for one or more records
print "$cnt.\t$_\n";
}
}
if ($cnt == 0) {goto NOT;} # No matches
next;
}
NOT:
print "Customer record not found. \n"; # Number or address not found
next;
}
print "\nAll done.\n"; # "q" was entered