queeg has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|