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

Hi everyone,
I am trying to pull the value of a hash key that has spaces. First off, let me show you the code and then I will ask my question.
my %hash = ( "Common SW Component" => "4885", "Test MMA" => "5130", "Generic key" => "5033", "Another generic key" => "4575", ); print "$hash{$variable}\n";

Now, say  $variable contains a hash key. If the hash key contains a space I get this error, "Use of uninitialized value in concatenation (.) or string" However, if I were to type in  print "$hash{'key with space'}\n"; the value gets returned. Is it possible to have the value returned with the  $variable having spaces? I hope this makes sense. Thanks in advance.

Replies are listed 'Best First'.
Re: Problems with Hash Keys and Spaces
by kyle (Abbot) on Aug 08, 2008 at 16:27 UTC

    Works fine for me. Are you sure $variable has in it what you think it has in it? Where are you getting the value? Have you tried to print it or dump it with Data::Dumper?

    my %hash = ( "Common SW Component" => "4885", "Test MMA" => "5130", "Generic key" => "5033", "Another generic key" => "4575", ); my $variable = "Another generic key"; print "$hash{$variable} ($variable)\n"; __END__ 4575 (Another generic key)
      Yes, the variable is actually being pulled from an array slot (number 1) and then matched against the key to return the numerical value. If I print the  $array[1] it returns exactly what the key should be, but when i plug it into the previous code I posted I get the error.

        Perhaps you could show us some more of the code you're using. The code you've posted so far doesn't show the problem.

Re: Problems with Hash Keys and Spaces
by tptass (Sexton) on Aug 08, 2008 at 16:29 UTC

    How are you defining $variable? I just ran your code with $variable set to "Another generic key" and received 4575 out. See code below:

    my %hash = ( "Common SW Component" => "4885", "Test MMA" => "5130", "Generic key" => "5033", "Another generic key" => "4575", ); my $variable = "Another generic key"; print "$hash{$variable}\n";
       my $variable = "$temp[1]";
        So, What's in $temp[1]?

        Add

        use Data::Dumper;

        Near the top of your program, and

        print Dumper \@temp;

        just before the line with the error


        Unless I state otherwise, all my code runs with strict and warnings
        Don't interpolate "$temp[1]". You may be losing information due to interpolation. Try this instead:
        my $variable = $temp[1];