in reply to Re: Tricky scope problem
in thread Tricky scope problem

Thank you mighty perl Monks for your wisdom! (this is the orginal poster, I'll have to make a user name at some point).
I do appologize for the confusion on debugging, all of your assumptions were correct and and the forloop was masking my outer variable. I was attempting to showcase the problem from a much larger program, after seeing your code snippits, I think I have a better idea of how to showcase things (I will read the linked page too, though I do point out, I knew what I meant, and you knew what I meant too, beginers luck?).
I have read many web pages on perl scoping (global vs lexical) including the documentation on key words 'my' and 'our' packaged within the perl install. I'm afraid I still think of "my $var;" used out side of a function as global to the file which would be its C/C++ equivalent and it appears to be the case in perl (excepting its use in forloops). I tend to think of using "our $var;" as the equivalent of an external command in C/C++, a way to link a file global var across mulitple files. Is this incorrect?
How does one declare a global variable if "use strict;" is in effect? As soon as I declare it via 'my', it is lexical not global.

Replies are listed 'Best First'.
Re^3: Tricky scope problem
by shmem (Chancellor) on Apr 13, 2009 at 19:52 UTC
    I tend to think of using "our $var;" as the equivalent of an external command in C/C++, a way to link a file global var across mulitple files.

    This is correct; but in all files this variable should be declared with our. But there's more to variables declared with 'our':

    • declaring a variable with 'our' creates a package global in the package in which it is declared
    • the short name of this variable is visible throughout its lexical scope, even spanning packages

    Example:

    package Foo; our $foo = 'foo'; # $Foo::foo now exists package main; print $foo,"\n"; # $Foo::foo, not $main::foo ! print $Foo::foo,"\n"; __END__ foo foo