Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

user defined variable as hash key index

by pleasehelp (Initiate)
on Oct 15, 2007 at 21:23 UTC ( #645030=perlquestion: print w/replies, xml ) Need Help??

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 (Chancellor) 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!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://645030]
Approved by kyle
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2019-08-21 00:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?