in reply to Variable in a foreach loop
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;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Variable in a foreach loop
by haukex (Archbishop) on Jul 14, 2016 at 13:15 UTC | |
by perldigious (Priest) on Jul 14, 2016 at 13:51 UTC |