After years of sloppiness I'm finally using 'strict'. I ran into some unexpected behaviour while adding 'use strict' to a working program.

The main part of the program is a foreach loop on a list. To save myself passing the value of the loop variable to a lot of subs, I want the loop variable to be global.

I thought that 'my $loop_var' at the start of the program would make it's scope the entire file, but that's not happening. Example:

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(); } #### sub print_color { print " in sub values are '$color' and '$light'\n"; }

gives:

$color is 'red' and $light is 'on' in loop, in sub values are '' and +'on' $color is 'green' and $light is 'on' in loop, in sub values are '' an +d 'on' $color is 'blue' and $light is 'on' in loop, in sub values are '' and + 'on'

$light works as I expected, but $color doesn't make it to the subroutine. If I use 'our $color' instead of 'my $color', I get the expected results.

I'm trying to understand why the foreach loop appears to narrow the scope of $color when using 'my,' but not when using 'our.' Any explanations?

Thanks,

Queeg


In reply to 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.