in reply to A way to avoid repeated conditional loops

Yet another way would be to set up a function(ref) which you just call for every line.  Initially, the called function checks for /alpha/, but once alpha is encountered, it replaces itself with the routine do_beta that is then called directly for the remaining beta lines. That way, the condition is no longer tested from there on.

my $f; $f = sub { if (/alpha/) { do_alpha(); $f = \&do_beta; } else { do_beta(); } }; while (<DATA>) { $f->(); } sub do_alpha { print "do_alpha(): \$f = $f, \$_ = $_"; } sub do_beta { print "do_beta(): \$f = $f, \$_ = $_"; } __DATA__ beta beta beta beta alpha beta beta beta beta beta beta beta beta

Output:

do_beta(): $f = CODE(0x796e88), $_ = beta do_beta(): $f = CODE(0x796e88), $_ = beta do_beta(): $f = CODE(0x796e88), $_ = beta do_beta(): $f = CODE(0x796e88), $_ = beta do_alpha(): $f = CODE(0x796e88), $_ = alpha do_beta(): $f = CODE(0x7c6ee8), $_ = beta do_beta(): $f = CODE(0x7c6ee8), $_ = beta do_beta(): $f = CODE(0x7c6ee8), $_ = beta do_beta(): $f = CODE(0x7c6ee8), $_ = beta do_beta(): $f = CODE(0x7c6ee8), $_ = beta do_beta(): $f = CODE(0x7c6ee8), $_ = beta do_beta(): $f = CODE(0x7c6ee8), $_ = beta do_beta(): $f = CODE(0x7c6ee8), $_ = beta

As you can see, the coderef changes after alpha has been encountered.

(upd: as it seems, BrowserUk posted essentially the same idea while I wrote up my reply...)

Replies are listed 'Best First'.
A reply falls below the community's threshold of quality. You may see it by logging in.