<?xml version="1.0" encoding="windows-1252"?>
<node id="149325" title="Re: Help needed understanding global variables in Perl" created="2002-03-05 05:44:27" updated="2005-07-21 01:31:00">
<type id="11">
note</type>
<author id="87452">
broquaint</author>
<data>
<field name="doctext">
&lt;i&gt;&amp;gt; how exactly do I define (rather than declare) a global variable in Perl&lt;/i&gt;&lt;br&gt;
The closest thing to a global variable are either "magical" variables or punctuation variables. Check out [id://141331|this node] for more info on globals.&lt;p&gt;
&lt;i&gt;&amp;gt;  is there any kind of "super" use strict, which helps me catch typos that my programs may have?&lt;/i&gt;&lt;br&gt;
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 [perlman:perltrap|the unwary].&lt;p&gt;
&lt;i&gt;&amp;gt; is there any way of defining a variable like C's static (i.e., a global variable with local scope)&lt;/i&gt;&lt;br&gt;
Not really. You can use a global variable in a local scope using the &lt;tt&gt;[perlfunc:local|local()]&lt;/tt&gt; function.
&lt;code&gt;
# use strict;
$foo = "a string";
sub bar {
    local $foo;
    print qq(foo is now localized and empty "$foo"\n);
}
&lt;/code&gt;
Or you could use a [closure] to create the imitation of a static variable
&lt;code&gt;
{   # 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 &amp;add_text
&lt;/code&gt;
&lt;i&gt;&amp;gt; In fact, I have trouble understanding the difference between our ($i); and use vars qw($i);&lt;/i&gt;&lt;br&gt;
The difference is that &lt;tt&gt;[perldoc://our|our()]&lt;/tt&gt; 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 &lt;tt&gt;use vars qw($x @y %z)&lt;/tt&gt; just declares it's arguments into the current package, and doesn't mess with the lexical scope.
&lt;br&gt;
HTH
&lt;p&gt;
broquaint
&lt;p&gt;
&lt;small&gt;Update: changed explanation of &lt;tt&gt;[perldoc://our|our()]&lt;/tt&gt; vs &lt;tt&gt;use vars qw($x @y %z)&lt;/tt&gt; per [rob_au|rob_au's] [id://149326|note]. Also realised why [tilly] has been knocking &lt;tt&gt;[perldoc://our|our()]&lt;/tt&gt; for so long ;-)&lt;/small&gt;&lt;br&gt;
&lt;small&gt;Update 2: also changed explanation of global variables per [shotgunefx|shotgunefx's] [id://149327|note]. /me thinks more research before posting might be an idea ...&lt;/small&gt;</field>
<field name="root_node">
149304</field>
<field name="parent_node">
149304</field>
</data>
</node>
