Question

I was hoping that someone might be able to assist me. I'm new to Perl and generally getting some good results from some small scripts I've written, however, I'm stuck on a nested while loop of a new script I'm working on.

The script I've put together performs two mysql select statements, and then places the results into to separate arrays. I then want to check from the first element in the first array against all of the results in the second array. Then move to the second element in the first array and check for against all results in the seconds array and so on.

The goal of the script is to find an IP address in the first array and see which subnets it fits into in the second...

What I find is happening is that the script runs through on only the first element on the first array and all elements on the second array, then stops.

Here is the extract of the perl script below - if anyone could point me int the right direction I would really appreciate it.

my @ip_core_wan_field;

while ( @ip_core_wan_field = $wan_core_collection->fetchrow_array() ) {
    my $coreipAddr = @ip_core_wan_field[1];
    my @ip_wan_field;
    while ( @ip_wan_field = $wan_collection->fetchrow_array() ) {
        my $ipAddr  = @ip_wan_field[1];
        my $network = NetAddr::IP->new( @ip_wan_field[4], @ip_wan_field[5] );
        my $ip      = NetAddr::IP->new($coreipAddr);

        if ( $ip->within($network) && $ip ne $ipAddr ) {
            print "$ip IS IN THE SAME subnet as $network \n";
        }
        else {
            print "$coreipAddr is outside the subnet for $network\n\n";
        }
    }
}
Was it helpful?

Solution

Your sql queries are single pass operations. If you want to loop over the second collection more than once, you need to either cache the values and interate over the cache, or rerun the query.

I would of course advise that you go with the first option using fetchall_arrayref

my $wan_arrayref = $wan_collection->fetchall_arrayref;

while ( my @ip_core_wan_field = $wan_core_collection->fetchrow_array() ) {
    my $coreipAddr = @ip_core_wan_field[1];

    for my $ip_wan_field_ref (@$wan_arrayref) {
        my @ip_wan_field = @$ip_wan_field_ref;

There are of course other ways to make this operation more efficient, but that's the crux of your current problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top