foreach causes $color to be an alias for $colors[0], $colors[1], and $colors[2]. In other words, if you were to assign "pink" to $color on each iteration through the loop, @colors would be filled with 'pink', 'pink', and 'pink'. But the lexical $color, outside of the loop, would remain undefined. This is because of the fact that $color, inside the loop, is a localized alias to the elements of the list you're iterating over. It just happens to be localizing the lexical $color. But when the loop exits, the localized effects are dropped, and $color reverts back to its original self.

The subroutine is defined outside of the loop, and therefore sees the version of $color that exists outside of the loop, and doesn't know about the localized aliases that are taking place inside the loop.

This is a somewhat sloppy version of a closure.

The proper way to pass data into a subroutine is as a parameter. You will find that if you rewrite your snippet with that in mind, your results will be more in keeping with what you predict them to be.

use strict; my @colors = qw ( red green blue ); my $color; my $light = 'on'; foreach $color (@colors) { print "\$color is '$color' and \$light is '$light' in loop, "; print_color( $color, $light ); } #### sub print_color { my ( $clr, $lite ) = @_; print " in sub values are '$clr' and '$lite'\n"; }

Also, if you want to preserve the last value of the loops iterator variable, you should play it safe by copying it to a variable that exists at greater scope, that hasn't been a part of the localized aliasing process.


Dave


In reply to Re: strict, scope, my and foreach - not behaving as expected by davido
in thread strict, scope, my and foreach - not behaving as expected by queeg

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.