Ng, Bill wrote:
Performance isn't really what I'm going for, just simpler code.
If clear code is what you want, you won't get it using a 'next' as some
have suggested. A 'next' syntactically looks like any other line, and
is therefore not easily noticed as part of the control flow. Unless,
perhaps, you put a big comment next to it. Like a 'return' or a 'die',
it's easily glanced over, and should only be used for exceptional
circumstances.
I recommend you either:
1. Embed the 'if' inside the 'for' - this makes it clear what you are
trying to do. It is not a significant performance penalty.
2. Filter out just the items you want to iterate over in advance,
using 'grep'.
First method:
@a = (1,2,3,4,5);
for (@a) {
if ($_ != 3) {
print "something";
&doSomething();
print "somethingelse";
&yada($yada{$ya});
}
}
Second method:
@a = (1,2,3,4,5);
for (grep { $_ != 3 } @a) {
print "something";
&doSomething();
print "somethingelse";
&yada($yada{$ya});
}
Personally, I think the second method is the clearest. You are
explicitly stating what you are iterating over. You might even write:
@a = (1,2,3,4,5);
@a_subset = grep { $_ != 3 }; # comment about why I only want these
for (@a_subset) {
...
}
Naming intermediate steps is good documentation.
The only reason I'd use the first method is if the condition for the
'if' could change during the iteration of the loop. But I try to avoid
those sorts of situations.
--
Lyle Kopnicky
Software Project Engineer
Veicon Technology, Inc.
_______________________________________________
Perl-Win32-Users mailing list
Perl-Win32-Users@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs