Search code examples
perlforeachscoping

Nested foreach loops in perl and variable scoping


Ok this is a little weird and it doesn't seem to should work this way. I have a foreach nested in another and I need it to only grab the values that correspond to the outer loop.

foreach my $var (@$list)
{
    foreach my $var2 (@$list2)
    {
        if($var2->[0] ne $var->[0])
        {
            print qq(They are equal);
        } else
        {
            next;
        }
    }
}

This doesn't seem to be working. Is there a rule I should know about for scoping in nested loops? Testing is showing that once the inner loop is entered $var ceases to exist until the inner loop exits.


Solution

  • It wouldn't seem to be working because you're testing if two strings are not equal and then printing that they are equal.

    Also you should make that print qq(They are equal\n);

    Incidentally, there is no issue with the scoping. Your strings are either matching or not matching--depending on which outcome you were expecting.