Can you show your complete code that your are attempting to run? I see no declaration or initialization for $max_cols or $max_rows. Assuming they exist elsewhere, this code would just print out the numbers 0 to whatever is in $max_rows a number of times equal to $max_cols+1 and then print the value of $max_rows one additional time.
EDIT: Ah, I think I see the behavior you are trying to illustrate. The last print actually doesn't get the last value ($max_rows) of the inner foreach loop despite the omission of my, it gets the original value scoped outside the loop (I added declarations and initializations).
use strict; use warnings; my $max_cols = 3; my $max_rows = 3; my $row_element = 0; my $col_element = 0; foreach my $col_element (0 .. $max_cols) { foreach $row_element (0 .. $max_rows) { print $row_element; } } print $row_element;
This isn't what I would have expected (obviously from my original post) either, but as haukex pointed out it does appear to be the intended behavior. I've never tried using a foreach loop without my. I guess you would be stuck doing something like this if you wanted the original scalar outside the foreach loop to update.
use strict; use warnings; my $max_cols = 3; my $max_rows = 3; my $row_element = 0; my $col_element = 0; foreach my $col_element (0 .. $max_cols) { foreach my $row_element_a (0 .. $max_rows) { $row_element = $row_element_a; print $row_element; } } print $row_element;
In reply to Re: Variable in a foreach loop
by perldigious
in thread Variable in a foreach loop
by ravi45722
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |