http://qs321.pair.com?node_id=149325


in reply to Help needed understanding global variables in Perl

> how exactly do I define (rather than declare) a global variable in Perl
The closest thing to a global variable are either "magical" variables or punctuation variables. Check out this node for more info on globals.

> is there any kind of "super" use strict, which helps me catch typos that my programs may have?
One of the reasons for using strict is to encourage the use of lexical variables and to move away from globals, which are can be a large cause of confusion to the unwary.

> is there any way of defining a variable like C's static (i.e., a global variable with local scope)
Not really. You can use a global variable in a local scope using the local() function.

# use strict; $foo = "a string"; sub bar { local $foo; print qq(foo is now localized and empty "$foo"\n); }
Or you could use a closure to create the imitation of a static variable
{ # creates a new lexical scope my $foo = "add text here - "; sub add_text { my $args = join '', @_; $foo .= $args; return $foo; } } # $foo now only referenced by &add_text
> In fact, I have trouble understanding the difference between our ($i); and use vars qw($i);
The difference is that our() declares the variable into the current package and is visible for the rest of the lexical scope (in my opinion this is very icky and kinda anti-DWIM). Whereas use vars qw($x @y %z) just declares it's arguments into the current package, and doesn't mess with the lexical scope.
HTH

broquaint

Update: changed explanation of our() vs use vars qw($x @y %z) per rob_au's note. Also realised why tilly has been knocking our() for so long ;-)
Update 2: also changed explanation of global variables per shotgunefx's note. /me thinks more research before posting might be an idea ...