So let's have fun with Perl variable scoping.

sub spam {
    my $mySpam = "my spam";
    our $ourSpam = "our spam";
    local $localSpam = "local spam";

    print "mySpam: " . $mySpam;
    print "ourSpam: " . $ourSpam;
    print "localSpam: " . $localSpam;

    spam2();
}

sub spam2 {
    print "mySpam: " . $mySpam;
    print "ourSpam: " . $ourSpam;
    print "localSpam: " . $localSpam;
}

spam();
print "mySpam: " . $mySpam;
print "ourSpam: " . $ourSpam;
print "localSpam: " . $localSpam;

Results:

mySpam: my spam
ourSpam: our spam
localSpam: local spam
mySpam: 
ourSpam: our spam
localSpam: local spam
mySpam: 
ourSpam: our spam
localSpam:


----------------
*** WARNINGS ***
----------------
Use of uninitialized value $mySpam in concatenation (.) 
    or string at C:\tmp\temp.pl line 14.
Use of uninitialized value $mySpam in concatenation (.) 
    or string at C:\tmp\temp.pl line 20.
Use of uninitialized value $localSpam in concatenation (.) 
    or string at C:\tmp\temp.pl line 22.

What's not to like about Perl scoping? Weird, weird language.

Pretty good summary at this SO answer that boils down to...

  • my is the most restrictive. Exists only between the nearest containing brackets.
  • local additionally gets shared with anything called within the nearest containing brackets.
  • our gets pushed everywhere within the script or module context (including things that import your module).

Mostly I'm just happy how well, relatively speaking, PerlRunner is working as a Perl !IDE. I really should take the time to integrate the syntax aware textbox from the CodeProject rather than continuing to hack away to get code editing behaviors in this one (like autoindent, faux tab deletion, and block tabbing). Honestly, his text box has everything, it appears: code folding, export to HTML, lazy-loading, column selection, even autocomplete if you set it up.

But sometimes it's fun to teach yourself to fish a little.

Labels: ,