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:
----------------------------------------
use strict;
use warnings;
use Net::Ping;
use Net::Netmask;
use Net::NBName;
use DBM::Deep;

# User-configured variable declarations
my @subnets = qw# 192.168.0.0/24 192.168.3.0/24 #; # @subnets
should only contain CIDR-type subnet address blocks
my @excludedIPAddresses = qw# 192.168.0.142 192.168.3.118 #; #
@excludedIPAddresses can only handle specific IP addresses for now
----------------------------------------
Further down, I use it in a subroutine:
----------------------------------------
sub ExcludeIPAddress
{
# Argument(s): IP Address (string) and $subnet (object reference)
# Returned: Boolean value corresponding to whether the IP should be excluded
# Globals: Uses @excludedIPAddresses (in user-config section)
my $ipAddress = shift @_;
my $subnet = shift @_;

# The next line does not work; I don't know why.
local @excludedIPAddresses = @excludedIPAddresses;
my $skip = 0;

push(@excludedIPAddresses, ($subnet->broadcast(),$subnet->base()));
$skip = grep /$ipAddress/, @excludedIPAddresses;

# Commented out original working code
# foreach my $exclude (@excludedIPAddresses)
# {
# $skip = 1 if ($ipAddress eq $exclude);
# }
return($skip);
}
----------------------------------------

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,

Because the local() function/keyword/operator applies to package
variables only. Not to lexical variables.

or what I should declare the variable as,
since if I leave out "my" I get an error using "use strict".

I don't understand why you're trying to assign a local value to this
variable to begin with. Why aren't you just declaring a new lexical,
and initializing it with the values currently in your "outer" lexical?

my @AllExcludedIPAddresses = @excludedIPAddresses,
$subnet->broadcast(),$subnet->base();
$skip = grep /$ipAddress/, @AllExcludedIPAddresses;


Or even, why bother declaring a variable at all? Why not just pass
that list to grep?

my $skip = grep /$ipAddress/, @excludedIPAddresses,
$subnet->broadcast(),$subnet->base();

Paul Lalli

.