Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Return lexical var to nested foreach

Status
Not open for further replies.

mt35

IS-IT--Management
Joined
May 29, 2004
Messages
2
Location
US
Hello,

I'm trying to pass a lexical variable down from one subroutine to another. I have read perlref on closure (among others) and grasp the concept for the situation they gave, however I think I'm trying to do something else entirely. Also I'm only two weeks old in perl so if I'm going about this in totally the wrong way pointers on the right way to go are appreciated.

I have an array of an ipfilter log (@fwlog) and a separate array of 10 addresses (@hirate), each of which will have an entry in the ipfilter log more than 15 times. I want to make an additional array (@hirate1) of the full log entry foreach address, thus weeding out all entries that do not correspond to the 10 address array (@hirate).

The original code with no closure performed on it:


foreach (@hirate) {
$y = $_;
foreach (@fwlog) {
push (@hirate1, $_) if ($_ =~ $y);
}
}

Example Variables:
$y = 192.168.1.81
@fwlog = Jan 4 03:01:02 host0 ipmon[51]: 03:01:01.088578 xl0 @0:1 b 192.168.1.81,1047 -> 192.168.1.100,53 PR udp len 20 61 OUT


The original problem I was having was @hirate1 would come out with a count of approx. 3000 when the original firewall log had a count of approx 1900.

Here is what I tried:

foreach (@hirate) {
$y = $_;
$q = max($y);
&$q();

sub max {
return sub {
foreach (@fwlog) {
push (@hirate1, $_) if ($_ =~ $y);
}
}
}
}

However, this brings back approx 3000 entires as well? Do I have some synatx wrong or am I going in the wrong direction altogether?


Thanks,

-SLM
 
You are redefining $_ in the second loop and thus redefining $y while your at it since $y is just a reference to $_. Just do this

Code:
foreach my $y(@hirate) {
   foreach (@fwlog) {
      push (@hirate1, $_) if ($_ =~ $y);
   }
}
 
Hi siberian,

Thanks for the help.

I actually found it was a problem in my search pattern. Say if I had 192.168.1.2 and 192.168.1.24 in my @hirate, when 192.168.1.2 ran through it would get all of it's own and all of 192.168.1.24, thus doubling count of 192.168.1.24.

I should of figured this out before...but I learned alot.

As far as my script goes, I think the outcome of assigning $y to $_ in the first pass was the same as doing $y(@hirate), however, your way is a much cleaner way of doing it and I'll continue to use that way.

Thanks again.

SLM



 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top