in reply to Re: strict, scope, my and foreach - not behaving as expected
in thread strict, scope, my and foreach - not behaving as expected
To answer some previous comments,
Why modify an existing program? I want to learn how to 'use strict' (to catch my tpyos) and to scope properly. This is a small, manageable program, and it's easier to understand and correct my mistakes now than after it grows. It's going to be part of a larger project that might even generate <gasp> income. So I want to write it well.
I'd like to ask 'why' too; why make the iteration variable global? Laziness. There are a few variables (including the outermost loop variable) that all the subs use , and rather than code and keep track of all the passing of parameters to subroutines, I made them global. Of course, I've spent more time trying to understand this issue than I ever would have passing parameters, but hey, that's how you learn.
What confused me was this: If I satisfy strict with
then I expect $color to be local to the loop. Whenforeach my $color (@colors) { ... }
outside of the loop satisfied strict for the loop variable $color I expected $color would be available outside of the loop during iteration. It wasn't.my $color;
There's still one question unanswered - if I use 'our $color' instead of 'my $color', the subroutine can see $color. I know that 'our' scopes globally, and I thought that 'my' at the beginning of the file, outside of any block, would scope to the whole file (effectively global), but it doesn't. So why are they different?
Thanks,
Queeg
use strict; my @colors = qw ( red green blue ); our $color; # our makes it work, my doesn't foreach $color (@colors) { print "\$color is '$color' in loop, "; too_lazy_to_code_passing_parameter(); } #### sub too_lazy_to_code_passing_parameter { print " in sub value is '$color'\n"; } $color is 'red' in loop, in sub value is 'red' $color is 'green' in loop, in sub value is 'green' $color is 'blue' in loop, in sub value is 'blue'
|
|---|