Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

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 ...

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.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page