in reply to Unable to extract value from hash table

Check the output of

use Data::Dumper; print Dumper \%TAGS;
$VAR1 = { 'CONST_STR' => 1 };

You're using the => when you don't mean to:

The => operator is a synonym for the comma, but forces any word (consisting entirely of word characters) to its left to be interpreted as a string (as of 5.001). This includes words that might otherwise be considered a constant or function call.

Solutions:

my %TAGS = ( CONST_STR, CONST_ID ); my %TAGS = ( +CONST_STR => CONST_ID ); my %TAGS = ( CONST_STR() => CONST_ID ); my %TAGS = ( &CONST_STR => CONST_ID );

Replies are listed 'Best First'.
Re^2: Unable to extract value from hash table
by dr_dunno (Novice) on Apr 09, 2008 at 06:24 UTC
    I tried the code below but it still keeps giving me the same error (Use of uninitialized value in print). I am sorry, I am new to Perl, so I might be missing something in your earlier reply.
    use constant CONST_STR => "MYSTRING"; use constant CONST_ID => 1; my %TAGS = ( CONST_STR, CONST_ID ); my $fullString = "123456 MYSTRING 123456"; my $string; ($string) = $fullString =~ /[A-Za-z]*/; print $TAGS{$string};

      When code doesn't do what you expect it to do,

      • Make sure the path of execution taken is the path of execution you expect the code to take. Investigate discrepancies.
      • Make sure variables hold the value you expect them to hold. Investigate discrepancies.

      There are two more errors in your code:

      • /[A-Za-z]*/ successfully matches the first 0 characters of $fullString, not what you want it to match.
      • Since there are no captures in /[A-Za-z]*/, it returns 1 on success even in list context.

      $string contains "1", and thus $TAGS{$string} is undef. Fix:

      my ($string) = $fullString =~ /([A-Za-z]+)/;

      (I moved the my. There's no reason for it to be on a separate line.)

        Oh, thanks so much for your help and sorry for the trouble. I am learning how to code in Perl and I made a silly mistake along the way (and I'm learning from them).