in reply to Re: Variable in a foreach loop
in thread Variable in a foreach loop

Hi perldigious,

... and then print the value of $max_rows one additional time.

ravi45722 is correct that the final print prints "0" - see my reply as to why.

use strict; use warnings; my $max_cols = 2; my $max_rows = 3; my $row_element = 0; foreach my $col_element (0 .. $max_cols) { foreach $row_element (0 .. $max_rows) { print "$row_element\n"; } } print "Last: $row_element\n"; __END__ 0 1 2 3 0 1 2 3 0 1 2 3 Last: 0

Regards,
-- Hauke D

Replies are listed 'Best First'.
Re^3: Variable in a foreach loop
by perldigious (Priest) on Jul 14, 2016 at 13:51 UTC

    Thanks haukex, I got there eventually, I just had to tweak the code so it would run to see that behavior and understand what ravi45722 was trying to point out. I would have been confused too if I had tried that and not dug through the foreach documentation, I always use my and explicitly update variables at a higher scope with assignments inside the loop body, so I've never seen this behavior before.

    I love it when things get difficult; after all, difficult pays the mortgage. - Dr. Keith Whites
    I hate it when things get difficult, so I'll just sell my house and rent cheap instead. - perldigious