SIVA
SIVA

Reputation: 11

How to access a local variable with in a foreach loop outside of its scope?

I have two arrays of string data type and i am comparing those using foreach loops and raising the counter when a match is found

my  @array1 = ('India');
my  @array2 = ('India', 'America');
foreach my $a (@array1) {
    foreach my $b (@array2) {
        my $count=0;  
        if($a eq $b) {
             $count++;
        }
    }
}

Now I want to use this count variable outside of its scope

 if ($count > 0) { 
      call_some_function();
 }

Where am I going wrong?

Upvotes: 0

Views: 285

Answers (2)

Flying_whale
Flying_whale

Reputation: 377

$count is declared into the foreach loop, it doesn't exist outside this loop, if you want to use $count outside the loop, simply put my $count=0 before the first foreach and remove the one into the foreach

here's what you want:

my @array1=('India');
my @array2=('India','America');
my $count=0;
foreach my $country1(@array1)
{
   foreach my $country2(@array2)
   {
        if($country1 eq $country2)
        {
             $count++;
        }

   } 
}

Upvotes: 3

Gareth O'Connor
Gareth O'Connor

Reputation: 60

Declare variable outside of the loops, you've also got a typo in $count:

my $count = 0;
foreach $a (@array1) {
   foreach $b (@array2) {
      if ( $a eq $b ) {
         $count++;
      }
   }
}

Upvotes: 0

Related Questions