Answers to Chapter 6 Exercises
Here’s one way to do it:
my %last_name = qw{ fred flintstone barney rubble wilma flintstone }; print "Please enter a first name: "; chomp(my $name = <STDIN>); print "That's $name $last_name{$name}.\n";In this one, we used a
qw//list (with curly braces as the delimiter) to initialize the hash. That’s fine for this simple data set, and it’s easy to maintain because each data item is a simple given name and simple family name, with nothing tricky. If your data might contain spaces—for example, ifrobert de niroormary kay placewere to visit Bedrock—this method wouldn’t work as well.You might have chosen to assign each key/value pair separately, something like this:
my %last_name; $last_name{"fred"} = "flintstone"; $last_name{"barney"} = "rubble"; $last_name{"wilma"} = "flintstone";Note that (if you chose to declare the hash with
my, perhaps becauseuse strictwas in effect) you must declare the hash before assigning any elements. You can’t usemyon only part of a variable, like this:my $last_name{"fred"} = "flintstone"; # Oops!The
myoperator works only with entire variables and never with one element of an array or hash. Speaking of lexical variables, you may have noticed the lexical variable$nameis being declared inside of thechompfunction call; it is fairly common to declare eachmyvariable as it is needed, like this.This is another case where
chompis vital. If someone enters the five-character string "fred\n" and we fail tochompit, we’ll ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access