Shashi Kiran
Shashi Kiran

Reputation: 71

for loop not incrementing after comparison

#!/usr/bin/perl -w                                                                                   
@success = qw(client1 client2 client3 client9);                                                      
print "the success array is @success\n";

@arr = qw(client3 client9);    
$asize = scalar(@arr);
$absize = scalar(@success);
@using  = qw(client2);

print "\n @using \n";
$usize = @using;

print "\n $asize $absize \n";

for ( $i = 0 ; $i < $asize ; $i++ ) {
    for ( $j = 0 ; $j < $absize ; $j++ ) {
        if ( $arr[$i] eq $success[$j] ) {
            print " \n $i $j ";
            print " before  $arr[$i] our choice\n";
            check( $arr[$i] );
            print "after check our choice \n";
        }
    }
}    ###end of t

sub check {
    print "################ checking client status $_[0] ###################### ";
    print "inside function call \n\n\n";

    our $sc = $_[0];

    for ( $j = 0 ; $j < $usize ; $j++ ) {
        if ( $sc eq $using[$j] ) {
            print "$sc is in use pls dont use \n";

            ###should we move to some file";
        }
        else {
            if ( $j eq $usize - 1 ) {
                print " reboot client\n";
                print "before reboot\n";
            }
        }
    }
}

hi

i am trying to check whether the content of "arr" array is in "success" array if its true i am checking whether that element is present in "using" array . but here it is going for infinite loop if the input client is client3 and client9 in "arr" array ..

thank you in advance

Upvotes: 0

Views: 278

Answers (1)

grebneke
grebneke

Reputation: 4494

The problem is this: You are using global variables all over. $j is used in both the main loop AND in sub check which causes a mess.

The quick fix is to change one of the for-loops to use my:

# in sub check:
for ( my $j = 0 ; $j < $usize ; $j++ ) {

The correct thing to do is:

Always use strict, use warnings and use my before all variable declarations in your script

#!/usr/bin/perl
use strict;
use warnings;
my @success = qw(client1 client2 client3 client9);
...
for ( my $i = 0 ; $i < $asize ; $i++ ) {
...

This has been discussed before here on SO. Also read perlintro on variable scoping (actually read the entire page)

Upvotes: 10

Related Questions