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. But if your data might contain spaces—for example, ifrobert de niroormary kay placewere to visit Bedrock—this simple method wouldn’t work so 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, never with just one element of an array or hash. Speaking of lexical variables, you may have noticed that 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 ...