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

Hello!

When i try access to hash with $name i get error:

Use of uninitialized value within %p in concatenation (.) or string at ./7.plx line 15, <STDIN> line 1.

#!/usr/bin/perl use warnings; use strict; use 5.010; my %p = ( "Word1" => "WordWord1", "Word2" => "WordWord2", "Word3" => "WordWord3", ); while(<STDIN>) { my $name = $_; print "$p{$name}\n"; }

What is wrong with my code?

Replies are listed 'Best First'.
Re: Wrong hash accessing?
by davido (Cardinal) on Mar 18, 2015 at 05:10 UTC

    You need to chomp your input.

    When the user types "Word1" and then hits <ENTER>, that <ENTER> gets included in the input string as a "newline" ("\n"). So the input string looks like "Word1\n". There is no hash key named "Word1\n", only "Word1".

    Or to put it another way, "Word1\n" and "Word1" would be two different keys.

    This will work as you seem to intend:

    while(<STDIN>) { chomp $_; # Remove the trailing newline from the contents of $_. my $name = $_; print "$p{$name}\n"; }

    Dave

      It is seems to be work. Thank you very much!