pleasehelp has asked for the wisdom of the Perl Monks concerning the following question:

Hi all! Can someone tell me why this doesn't work?

#!/usr/bin/perl use warnings; use strict; my %numbers=( nameA => "1234567", nameB => "2234567", nameC => "3234567", nameD => "4234567", nameE => "5234567" ); print "Who's number are you looking for? : \n"; my $who = <STDIN>; print "$who number is $numbers{$who}\n";

this is the output i get:

C:\BegPerl\chap3\Exercises>chap3_ex3.pl Who's number are you looking for? : "nameA" Use of uninitialized value in concatenation (.) or string at C:\BegPerl\chap3\Exercises\chap3_ex3.pl line 21, <STDIN> li ne 1. nameA number is

Replies are listed 'Best First'.
Re: user defined variable as hash key index
by FunkyMonk (Bishop) on Oct 15, 2007 at 21:27 UTC
    You need to chomp your input to get rid of the newline:
    print "Who's number are you looking for? : \n"; my $who = <STDIN>; chomp $who; print "$who number is $numbers{$who}\n";

    Code look much better if you wrap it in <code> ... </code> tags :-)

      THANKS dude! The book i'm learning from has yet to introduce chomp so i don't really know what they expected.
Re: user defined variable as hash key index
by naikonta (Curate) on Oct 16, 2007 at 01:12 UTC
    Additionally from FunkyMonk's answer, you may also want to put some checking to see if supplied name doesn't exist in %numbers to avoid unitialized warning.
    print "Who's number are you looking for? : \n"; chomp(my $who = <STDIN>); my $number = $numbers{$who} || 'unknown'; print "$who number is $number\n";

    Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!