in reply to strict, scope, my and foreach - not behaving as expected
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: strict, scope, my and foreach - not behaving as expected
by queeg (Novice) on Jun 09, 2004 at 20:54 UTC |