Well, I was out in space, here. It's not a scoping problem
at all, as others have mentioned.
Oh, well.
ReadPhoneBookFile() cannot "see" %PhoneBook, because
%PhoneBook is lexical.
Okay, here is the code after I made a few changes to it.
use strict;
use vars qw/%PhoneBook/;
# Read in CSV phone book
ReadPhoneBookFile();
# Run two parameter tests
my $ValidTest = "8594";
my $InvalidTest = "9999";
print "Parameter test 1 - Number to find is: $ValidTest\n";
print 'The caller was: ', MatchPhoneNumber($ValidTest), "\n";
print "\nParameter test 2 - Number to find is: $InvalidTest\n";
print 'The caller was: ', MatchPhoneNumber($InvalidTest), "\n";
exit;
sub ReadPhoneBookFile
###
### Reads in a CSV separated phone book, splits, stuffs details into
+a hash
###
### In real-world script, data is read from an external file.
{
foreach (<DATA>) {
my @Details = split(/,/,$_);
$PhoneBook{$Details[0]} = $Details[1];
}
}
sub MatchPhoneNumber
###
### Attempts to match the phone number with a name from the phonebook
### Either returns the caller name if number in hash or "Unknown calle
+r".
###
{
my $NumToFind = shift;
return defined $PhoneBook{$NumToFind}
? $PhoneBook{$NumToFind}
: 'Unknown Caller';
}
__DATA__
8594,Tom
9000,Dick
1234,Harry
A few notes:
- You had 8954 in some places, and 8594 in others
- As noted above, %PhoneBook was lexical, therefore not
in scope when ReadPhoneBookFile() and MatchPhoneNumber()
were called.
- We use use vars to put %PhoneBook in the
symbol table for this scope and keep use strict
happy.
- We could also just pass %PhoneBook to the
functions. Many would argue this is a better way...
- I removed many of your temporary variables. This is
mainly just an issue of performance and style. No offense...
So, it was just a scoping issue...
Russ
Brainbench 'Most Valuable Professional' for Perl
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.