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

I am trying to use a hash table which is made up of a constant string as the key and a constant number as the value. However, when I run the script, I get an error "Use of uninitialized value in print".

---------------------------------------------------- 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}; ----------------------------------------------------
Any idea how I can get this to work?

Replies are listed 'Best First'.
Re: Unable to extract value from hash table
by ikegami (Patriarch) on Apr 09, 2008 at 06:12 UTC

    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 );
      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.)

Re: Unable to extract value from hash table
by fmerges (Chaplain) on Apr 09, 2008 at 09:17 UTC

    Hi,

    Think about if you need or want to use constant you can use Readonly & Readonly::XS instead. It even allows you to have lexical constants

    Regards,

    fmerges at irc.freenode.net