i wanted to write
my @doubles = (* * 2 for 4..8);
.say for @doubles;
to get
8
10
12
14
16
but forgot the parentheses and got
{ ... }
because what this code actually do is
my @doubles = * * 2;
but 4 times :)
for me, this is nonsense:
if the scope of "my @doubles" is the for loop, then the line 2 should rise an error.
Variable '@doubles' is not declared
if the scope is global, there should be an error on the first line
Redeclaration of symbol '@doubles'
but at least, it would be nice to have an error message because there is no
reason to do what i did and the problem is not obvious to spot in a large codebase.
I understand your frustration but have to say, I disagree strongly with your proposal. Assignment has a tighter precedence than the for loop so it isn't unexpected that it would yield that result when the grouping parenthesis are omitted. As for reinitializing a variable for each iteration of a loop; that's an extremely common and desirable feature. It would be a major change to the whole language and culture to disallow it.
It _might_ be possible to come up with some kind of "useless assignment" warning for variables that are assigned but never used... but I could see that generating all kinds of false positives and being more problematic than it is likely worth. (Not even taking into account the limited and precious developer time to do so, which could be better spent in myriad other ways.)
On another note: If you are generating values by mapping a transform to a range. you may be better using map than for.
my @doubles = map * * 2, 4..8;
say @doubles;
thanks. i wasn't aware this pattern can be useful and it still confuses me (because of 4 declarations of the same symbol in the same scope) but i agree that my proposal is unacceptable if people find it legit.
A couple of quick notes:
my $a += 10 for 1..5; say $a and get 50, which is rather more useful.
Most helpful comment
I understand your frustration but have to say, I disagree strongly with your proposal. Assignment has a tighter precedence than the for loop so it isn't unexpected that it would yield that result when the grouping parenthesis are omitted. As for reinitializing a variable for each iteration of a loop; that's an extremely common and desirable feature. It would be a major change to the whole language and culture to disallow it.
It _might_ be possible to come up with some kind of "useless assignment" warning for variables that are assigned but never used... but I could see that generating all kinds of false positives and being more problematic than it is likely worth. (Not even taking into account the limited and precious developer time to do so, which could be better spent in myriad other ways.)
On another note: If you are generating values by mapping a transform to a range. you may be better using map than for.