Anonymous Monk,
No, what I am asking for is not a special case of "loop enlightment". What I am asking for is for people to consider what they would do if they had the ability to modify the optree (or the p6 equivalent) while the code is running.
To answer you code question - consider the following trivial example:
for ( @some_array ) {
if ( $_ eq 'foo' ) {
print "skipping foo\n";
next;
}
if ( $_ eq 'bar' ) {
handle_bar($_);
next;
}
handle_rest($_);
}
To re-write this we need to first change
for ( @some_array ) { ... }
# to
my $index = -1;
while ( ++$index <= $#some_array ) { ... }
So that when we break out of the first loop to enter the second, we can remember where we left off. Unfortunately, the order that we will encounter 'foo' and 'bar' is unknown so we also have to create a flag variable and end up with 4 while loops instead of the original 1:
my $flag;
my $index = -1;
while ( ++$index <= $#some_array ) {
if ( $_ eq 'foo' ) {
$flag = 'foo';
print "skipping foo\n";
last;
}
if ( $_ eq 'bar' ) {
$flag = 'bar';
handle_bar($_);
last;
}
handle_rest($_);
}
if ( $flag eq 'foo' ) {
while ( ++$index <= $#some_array ) {
if ( $_ eq 'bar' ) {
handle_bar($_);
last;
}
handle_rest($_);
}
}
else {
while ( ++$index <= $#some_array ) {
if ( $_ eq 'foo' ) {
print "skipping foo\n";
last;
}
handle_rest($_);
}
}
while ( ++$index <= $#some_array ) {
handle_rest($_);
}
This was a translation of a very simple example. I do not if there is any case where it would be impossible to do, but it certainly isn't easy. Again, the point of the medidation is to just take the functionality as a given for a second and think about what you would do with it.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.