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

Hi all I realy don't understand why I dont get "Global symbol "%CS101" requires explicit" when I run:

#!/usr/bin/perl # use warnings; use strict; use Carp; use 5.016; ave(); my %CS101 =("Joe Below" => 100, "Dan Gold" => 90, "Jon Kery" => 40, "Elton Jon" => 60, ); sub ave { foreach (keys %CS101) { print $CS101{$_}, "\n"; } } 1; __END__

It only wotks if I put the hash at the top. Thanks in advance. Adrian

Replies are listed 'Best First'.
Re: subroutine no error
by Anonymous Monk on Jul 23, 2014 at 10:53 UTC

      Big thanks, you are definitely right.

Re: subroutine no error
by AppleFritter (Vicar) on Jul 23, 2014 at 10:27 UTC

    Howdy adriang, welcome back to the Monastery!

    You're only declaring %CS101 after calling ave(), so at the time ave is running, it does not exist yet and therefore can't be accessed. Move the declaration to somewhere before the subroutine call, and all will be fine.

      Thanks for the quick replay. Yes, this is true but the question is why I didn't get any error? Thanks in advance

        Good question, actually: and my apologies, I misread your post.

        Looking at the script again, I think that the reason is as follows. When Perl compiles your script, the fact that ave is called before %CS101 doesn't matter: by the time the Perl compiler gets to the body of ave, %CS101% has been declared and thus can be accessed.

        However, when Perl runs your script, ave is called before %CS101 gets assigned a value, so the hash is empty and you don't get any output.