Answers to Chapter 6 Exercises

  1. 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, if robert de niro or mary kay place were 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 because use strict was in effect), you must declare the hash before assigning any elements. You can’t use my on only part of a variable, like this:

    my $last_name{"fred"} = "flintstone";  # Oops!

    The my operator 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 $name is being declared inside of the chomp function call; it is fairly common to declare each my variable as it is needed, like this.

    This is another case where chomp is vital. If someone enters the five-character string "fred\n" and we fail ...

Get Learning Perl, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.