in reply to Surpised by foreach iterator limitation
But that intuitive sense seems to be wrong in a subtle way. Many of us have relied on the documented behavior that results in things like:
As pointed out by "perldoc perlsyn": 'the "foreach" loop index variable is an implicit alias for each item in the list that you're looping over.' Another passage from perlsyn, very close afterwards, points out: '"foreach" probably won't do what you expect if VAR is a tied or other special variable. Don't do that...'my @array = qw/1 2 3 4/; foreach my $elem ( @array ) { $elem *= 5; } print join " ",@array,$/; __OUTPUT__ 5 10 15 20
Next, we'd have to look closely at how perl stores variables internally (The Damian's excellent book "Object Oriented Perl" has one of the nicest explanations), and try to work out how different a hash element is from a normal scalar. Well, it's late, and I won't try that just now... The point is that the loop variable is not being used as an lvalue -- it's something else with special properties.
update: Regarding perl implementation issues, I would suppose that the compiler has a very rigid sense of for-loop syntax: the thing after "for" (or "foreach") must be a scalar; if there's a curly brace after that, it probably interprets this as the start of a block (not a hash index), and reports the syntax error because there's no list being provided for the iteration. Of course, the error is reported if you're using an array element (square-brackets) as well.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Surpised by foreach iterator limitation
by MarkM (Curate) on Apr 08, 2003 at 03:24 UTC | |
|
Re: Re: Surpised by foreach iterator limitation
by shotgunefx (Parson) on Apr 08, 2003 at 09:15 UTC |