Hi pritesh_ugrankar,
Yes, it's OK to use a single variable to iterate through multiple arrays:
perl -Mstrict -WE '
my @x = (1,2);
my @y = (3,4);
for my $z ( @x, @y ) {
say $z;
}
'
Output:
1
2
3
4
If you want to iterate through your arrays one at a time, you can still use the same variable name, since it will be local to the for loop:
perl -Mstrict -WE '
my @x = (1,2);
my @y = (3,4);
for my $z ( @x ) {
say $z;
}
for my $z ( @y ) {
say $z;
}
'
Output:
1
2
3
4
For the same reason (locally scoped variable) you can use the same variable name even with nested loops:
perl -Mstrict -WE '
my @x = (1,2);
my @y = (3,4);
for my $z ( @x ) {
say $z;
for my $z ( @y ) {
say " $z";
}
say $z;
}
'
Output:
1
3
4
1
2
3
4
2
... although this is rarely a good idea, since it makes it less easy to follow the flow of the code.
Variable names are free; go ahead and use another one!
Hope this helps!
The way forward always starts with a minimal test.
|