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;

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

In reply to Re: Variable in a foreach loop by perldigious
in thread Variable in a foreach loop by ravi45722

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.