in reply to Re^2: loop surprise
in thread loop surprise
Hi morgon,
say
substr+lc crypt(qw $i3 SI$),4,5
I wouldn't say it's that Perl "knows better" so much as that it's a convenience for being able to modify the data you're iterating over.
Note that, because it's only a foreach loop that acts this way, and for is this context is just an alias for the same thing, if you want the behavior you were expecting you can use the 3-arg form of a for loop:
And believe it or not, you could even make it a 3-arg foreach loop (which is kinda counter-intuitive, but again, "for" and "foreach" are interchangeable):use strict; my $i = "whatever"; for ($i = 1; $i <= 10; $i++) { last if $i == 7; } print "$i\n"; # prints "7" instead
use strict; my $i = "whatever"; foreach ($i = 1; $i <= 10; $i++) { last if $i == 7; } print "$i\n"; # still prints "7"
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^4: loop surprise
by morgon (Priest) on Apr 03, 2018 at 18:00 UTC | |
by Your Mother (Archbishop) on Apr 03, 2018 at 18:21 UTC | |
by morgon (Priest) on Apr 03, 2018 at 20:50 UTC | |
by Your Mother (Archbishop) on Apr 04, 2018 at 00:38 UTC | |
by Skeeve (Parson) on Apr 04, 2018 at 10:02 UTC | |
by Marshall (Canon) on Apr 04, 2018 at 17:59 UTC | |
by BillKSmith (Monsignor) on Apr 04, 2018 at 04:18 UTC |
In Section
Seekers of Perl Wisdom