From: "Charles K. Clarkson" <[EMAIL PROTECTED]>
To: <beginners@perl.org>
Date: Thu, 31 Aug 2006 10:41:33 -0500
Subject: RE: Trouble with variable scoping
Roman Daszczyszak wrote:

: In my perl script, I have a "global" variable called
: @excludedIPAddresses, declared at the top of the script using
: my.

    That sounds like a bad idea, but go on.
It is but it's just for my convenience.  The variables in question are
ones that I change on the fly but do not want to type in repeatedly at
the command-line or use a separate configuration file.  They're at the
top so I don't have to hunt for them.

I did figure out I should just leave it 'my' scoped and pass the
variable to the subroutine.  Easier than trying to figure out how to
make a global work.. at least for me.

: When I run this, I get an error "Can't localize lexical
: variable". I understand that it's because the variable is
: declared using "my"; what I don't understand is why, or what I
: should declare the variable as, since if I leave out "my" I get
: an error using "use strict".

    Don't use local() in this circumstance.

sub ExcludeIPAddress {
    my $ipAddress = shift;
    my $subnet = shift;

    return scalar grep /$ipAddress/,
        @excludedIPAddresses,
        $subnet->broadcast(),
        $subnet->base();
}



HTH,
It does, and I had thought about doing it that way, but I am still
curious about the answer to my question, which I suppose is better
stated:
    What is the scope of a variable that is declared at the top of a
file using 'my'?
I had thought that this would just make a variable that is scoped to
the entire file, yet 'local' does not localize the variable in a
subroutine, even though it (local) according to what I've read will
'save a global variable's value and reset it back upon the variable
going out of scope'.  That sounded exactly like the behavior I was
after, yet it did not work.  According to the error, 'local' does not
work on lexically scoped variables.. so what other kinds of scoping
are there?  I only know of using 'my' to declare variables (which are
scoped to the current block (which I understand) and are lexically
scoped (which I don't)) because it's required by 'use strict'.

I hope this helps explain my current confusion.
Regards,
Roman

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to