perl help

Hey guys, I am teaching myself perl, and I am having some problems. Should be easy… I just can’t figure out why it won’t work, the problem is with the last line of the script.

The second question I have is why does the $input variable output on a new line? I didn’t specify
anywhere, does it take a bunch of whitespace into the variable? If so, how do I eliminate that?

Thanks! :slight_smile:

#!/usr/bin/perl
#
# Phonebook in Chapter 3 quiz.

use warnings;
use strict;


print "Please enter a name: ";

my $input = <STDIN>;


my %phone=(
        Debbie  => "555-1234",
        Greg    => "555-1232",
        Bob     => "555-2435",
        Steve   => "555-0213",
        Les     => "555-3021",
        Harold  => "321-2010"
);

print "$input has a phone number of: ", $phone{$input},"
";

Output:
Hilikus@Cronos:~/Scripting/Perl> perl phone.plx
Please enter a name: Debbie
Debbie
Use of uninitialized value in print at phone.plx line 23, <STDIN> line 1.
has a phone number of:

When you read input with $input = <STDIN>, the string includes the newline at the end. So there was no such key = "Debbie
". The idiom is to strip trailing newlines with:

chomp $input;

For robustness you should also trim leading and trailing whitespace from your string, otherwise if this is input by the user, there will be no record found. It will be looking for something like $phone{"Debbie "}. Trim exercise left to you.

Thanks a bunch, I knew it was something simple. :slight_smile: Got it working.

chomp will come in very handy I can imagine… that has yet to be covered in the book I am using.
Thanks again.