Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Global symbol .... requires explicit package name at

by bv (Friar)
on Oct 19, 2009 at 18:06 UTC ( #802061=note: print w/replies, xml ) Need Help??


in reply to Global symbol .... requires explicit package name at

use diagnostics

Global symbol "$files" requires explicit package name at 1.pl line 19. Execution of 1.pl aborted due to compilation errors (#1) (F) You've said "use strict" or "use strict vars", which indicates + that all variables must either be lexically scoped (using "my" or +"state"), declared beforehand using "our", or explicitly qualified to say which package the global variable is in (using "::").

The variable $files isn't lexical. foreach (and for) uses $_ by default, but if you specify a variable name before the list, it's roughly equivalent to

foreach (@files) { $files = $_; #etc...

So to be properly strict, you need to use my. Here are some examples of odd places where you would have to use my:

for my $i ( 0 .. 10 ) { print "$i\n" } open my $fh, '<', "/etc/passwd"; while (my $line = <>) { next if /^\s*#/ }
print pack("A25",pack("V*",map{1919242272+$_}(34481450,-49737472,6228,0,-285028276,6979,-1380265972)))

Replies are listed 'Best First'.
Re^2: Global symbol .... requires explicit package name at
by GrandFather (Sage) on Oct 19, 2009 at 19:55 UTC

    The variable $files isn't lexical. foreach (and for) uses $_ by default, but if you specify a variable name before the list, it's roughly equivalent to

    foreach (@files) { $files = $_; #etc...

    Actually, not even roughly! The loop variable is an alias to each element of the list processed by the for loop so indicating an equivalence using assignment is quite misleading.

    The OP should note that a for loop variable is magical and is only valid within the scope of the loop. A same named variable outside the loop, even if declared as a lexical variable using my, is a different animal to the loop variable. Consider:

    use strict; use warnings; my $var = 42; print "before: $var\n"; for $var (1 .. 10) { print "$var "; } print "\nafter: $var\n";

    Prints:

    before: 42 1 2 3 4 5 6 7 8 9 10 after: 42

    True laziness is hard work

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://802061]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2019-12-08 02:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (162 votes). Check out past polls.

    Notices?