O'Reilly logo

Learning Perl Student Workbook, 2nd Edition by brian d foy

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix F. Answers to Chapter 6 Exercises

Answer 6.1: Most of this problem is simply creating the hash. There is nothing fancy about it: you just have to type it in. In %birthdays, use a single line for each key-value pair and use the big arrow operator, =>, to separate the keys and values. The big arrow automatically quotes the string on its left. You can also line up the big arrows to create easy-to-read columns.

To report the contents of the hash, go through it with a foreach loop. With each of the keys, output a line that includes the name and the birthday and look up the value directly in the double-quoted string:

#!/usr/bin/perl
use strict;
use warnings;

my %birthdays = (
    Fred    => 'April 5',
    Wilma   => 'October 26',
    Pebbles => 'October 8',
    );
 
foreach my $name ( keys %birthdays ) {
    print "$name => $birthdays{$name}\n";
    }

Here’s a sample run:

$ perl ex6.1.pl
Pebbles => October 8
Wilma => October 26
Fred => April 5

Answer 6.2: Take the hash that you created in the Answer to Exercise 6.1. Prompt the user for a name then read a line from standard input and store it in $name. You don’t want the newline on the end of the input, so remove it with chomp.

Once you have the name, output a message. Look up the value and interpolate it directly in the double-quoted string:

#!/usr/bin/perl use strict; use warnings; my %birthdays = ( Fred => 'April 5', Wilma => 'October 26', Pebbles => 'October 8', ); print "Enter a name: "; chomp( my $name = <STDIN> ); print "$name has a birthday on $birthdays{$name}\n"; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required