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

A fairly simple code to load a file into a hash of keys and values. I declared my hash before the while loop globally, but when I try to use $hashofstates->($key) = $val; it throws me an error as if it wasnt declared. What could possibly be wrong?

use strict; use warnings; use Data::Dumper; my $File = "inp.txt"; open FILE, '<' , $File or die $!; my %hashofstates; while (my $line=<FILE>) { chomp $line; my ($key, $val) = split /\s+/, $line ,2; $hashofstates->($key) = $val; } close FILE or die 'Could not close file'; print (values \%hashofstates);

Error:

perl prog.pl Global symbol "$hashpfstates" requires explicit package name

Replies are listed 'Best First'.
Re: Error hash declaration
by NetWallah (Canon) on Aug 30, 2014 at 00:12 UTC
    my %hashofstates; << This declares a hash : "%hashofstates" .

    $hashofstates->($key) << This attempts to access a SCALAR REFERENCE : "$hashofstates" , a totally different animal that does not exist.

    The distinction between the hash and the hash-ref is the use of the DEREFERENCING operator "->".

    You probably wanted:

    $hashofstates{$key}
    Also note the use of Curly brackets (Not parens) to contain hash keys.

            "You're only given one little spark of madness. You mustn't lose it."         - Robin Williams

      Thankyou!
Re: Error hash declaration
by AppleFritter (Vicar) on Aug 30, 2014 at 09:37 UTC

    Global symbol "$hashpfstates" requires explicit package name

    Look closely: it says "hashpfstates", not "hashofstates". So in addition to what NetWallah said, you have (or had) a typo there.

Re: Error hash declaration
by AnomalousMonk (Archbishop) on Aug 30, 2014 at 17:12 UTC
    $hashofstates->($key) = $val;

    FWIW, this statement attempts to de-reference  $hashofstates as a subroutine reference, invoking it and passing  $key to it as an argument, and to assign  $val to an lvalue exposed (if that's the right terminology) by the subroutine. All of this is possible in another Perl code-world, but as others have written, with the OPed code it's na'gonna happen.