in reply to Re: loop surprise
in thread loop surprise
Personally, I wouldn't break out on a condition related to the value of $i itself in such a loop, but I often run across circumstances such that I want to use the loop variable to store the last condition that was valid, when looping through a list of valid or invalid conditions. For example,
... That loop wouldn't work in perl. But it doesn't seem an abuse of the loop counter, to me, to use the loop counter as the indicator of how many situations were actually tested. The code above seems more natural to me thanmy $condNum = 0; for $condNum ( 1 .. 10 ) { forceSituation( $conditions[condNum] ); my $result = measureSituation(); push @results, $result; last if $result->is_error(); more_manipulation(); # possibly do more stuff for this condition, +but only if it's not an error } datalog( value => $condNum, llim => 9.9, hlim => 10.1, name => 'number + of situations tested' ); datalog( value => fn(@results), llim => -2.7182818, hlim => 3.1415926, + name => 'result of those situations' )
Why require a second variable just to store the last condition number it happened to be in, when the loop variable seems a natural storage device for that information?my $lastCondNum = 0; for my $condNum ( 1 .. 10 ) { ... $lastCondNum=$condNum, last if $result->is_error() ... } ...
(In these situations, I'm generally in a hardware-specific language, not Perl, so that one annoyance of Perl doesn't usually affect me. But there are a plethora in the hardware-specific language that I wish it did more like Perl does, so not a fair balance, in my opinion. :-( )
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: loop surprise
by AnomalousMonk (Archbishop) on Apr 03, 2018 at 18:48 UTC | |
by pryrt (Abbot) on Apr 03, 2018 at 19:08 UTC | |
by choroba (Cardinal) on Apr 03, 2018 at 20:23 UTC | |
by pryrt (Abbot) on Apr 03, 2018 at 20:41 UTC | |
|
Re^3: loop surprise
by Your Mother (Archbishop) on Apr 03, 2018 at 18:30 UTC | |
|
Re^3: loop surprise
by QM (Parson) on Apr 04, 2018 at 10:08 UTC |