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 (@$l开发者_开发技巧ist2)
{
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.
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.
I don't think scoping is your problem. You used ne and then printed "They are equal". If you're expecting them to be equal you should use eq. See below:
foreach my $var (@$list){
foreach my $var2 (@$list2){
if($var2->[0] eq $var->[0]) {
print qq(They are equal);
} else {
next;
}
}
}
I think it is scope problem here since I face the problem in my code. when I print the variable in the outer foreach it printing correctly, but when I try to print the outer foreach variable inside the inner foreach it only print the initialized value of the outer variable.
精彩评论