Perl global symbol requires an explicit package name

I am trying to save log messages in a hash depending on the type of message, as shown below:

#!/usr/bin/perl use strict; use warnings; my %log; opendir (DIR, '.') or die $!; while (my $file = readdir(DIR)) { # some code to select TAR filename in $1 if (-e $1.'.tar') { push(@{$log->{$1}}, $file); /* line 12 */ } else { $log{$1} = []; push(@{$log->{$1}}, $file); /* line 16 */ } 

Now this code gives a compilation error:

 Global symbol "$log" requires explicit package name at at lines 12 & 16 

where I'm really trying to use the hash "% log". What could be a possible way to get rid of this error? Why is this exactly happening?

I saw some explanations in a context where people answered that the variables were created in one context and passed in another, but I believe that this variable should be available inside the while loop in this piece of code. This only happens when I β€œuse strict” and works fine otherwise.

I started with Perl, so I do not fully understand the basics! Please help me understand why this variable is not available.

+4
source share
2 answers
 my %log; 

defines hash %log , but lines 12 and 16 do not use it. Instead, you access an anonymous hash referenced by a $log scalar that you never declared. You have two options.

  • You can continue to use an anonymous hash.

     my $log = {}; # The creation of the hash ("{}") is currently being done # implicitly by "->". This is called autovivification. ... $log->{...} ... 

    This adds a bit of extra complexity and an imperceptible speed reduction.

  • You can use the hash directly.

     my %log; ... $log{...} ... 
+9
source

I'm not sure what you are trying to do with $1 , but hash access is not a link, so change:

 $log->{$1} 

to

 $log{$1} 

The error message you received says: Global symbol "$log" requires explicit package because the $log variable is not defined. Remember that %log and $log are two different variables (hash vs scalar).

+9
source

All Articles