in reply to Re: A way to avoid repeated conditional loops
in thread A way to avoid repeated conditional loops

You can't rely on readline returning EOF or errors more than once. Fix:

OUTER: { for (;;) { defined( my $_ = <$fh> ) or last OUTER; if (/alpha/) { f(); last; } else { g(); } } while (<$fh>) { g(); } }

Update: The remainder of this post is wrong.

You can get rid of the duplicate g() by making the loops bottom tested.

OUTER: { defined( my $_ = <$fh> ) or last OUTER; for (;;) { if (/alpha/) { f(); last; } defined( $_ = <$fh> ) or last OUTER; } for (;;) { g(); defined( $_ = <$fh> ) or last OUTER; } }

You can squish it down a bit:

LOOP: { defined( my $_ = <$fh> ) or last; if (/alpha/) { f(); redo; } for (;;) { g(); defined( $_ = <$fh> ) or last; } }

Look at that, g() is not even duplicated anymore!!

Replies are listed 'Best First'.
Re^3: A way to avoid repeated conditional loops
by jffry (Hermit) on Aug 24, 2011 at 19:39 UTC

    Why is your for loop idiom better than AR's or JavaFan's while loop statements above?

      I already pointed out that AR's version is wrong. You can't rely on readline returning EOF or errors more than once.

      I thought mine was better than JavaFan's because it lead to the elimination of the duplicate "g()", but that turned out to be a mistake (as per my earlier update).

      I still prefer mine over JavaFan's, though. Since mine flows from top to bottom, it requires less skipping around to follow the code.

        Ah! Now I see what you're saying.

        Using AR's code, suppose the file is empty, then the very first while (<FILE>) will return EOF, then the code flows to the second while (<FILE>). There, even though the file pointer is at the end of the file, the <> operator won't return an EOF a second time. And the code in that second while loop will get executed when it should not.

        Thinking of it this way, I can now see how both yours and JavaFan's code avoid that trap. Thanks.

Re^3: A way to avoid repeated conditional loops
by Deus Ex (Scribe) on Aug 25, 2011 at 13:41 UTC

    The squished version is really cool :) It looks I got my solution!

    Many thanks ikegami!

      That version doesn't do anything until it reaches the first alpha. Is that really what you want?

        You're right. Was naming the first block of code you wrote as "the squished version". Of course it was not :)

        Actually I've been realizing that there's no way other than using either a regex to test on the evaluated current line or a flag variable. At this point it seems to me the second approach might be the most efficient in computational terms. Many thanks for your help :)