It's reading through a file and it wants to exit the read loop on any of three conditions: At end-of-file; at a line that begins with \037, or at a line that begins with * Menu:. In the first two cases the function should return immediately, but if it sees * Menu: it should continue to the next block of code, which reads and processes the following menu.$_ = <INFO> until !defined($_) || /^(\* Menu:|\037)/; return %header if !defined($_) || /^\037/;
I don't really like the code above, because it seems redundant. The two pattern matches are similar but not identical, and the test for defined($_) is repeated. Usually in such cases there's a way to rewrite the block without repetition. I messed around with this a while, but wasn't able to come up with anything I was really happy with.
Here's one possibility:
This avoids the repeated regex, but the defined test is still repeated (although implicitly) and the return is also repeated. I kept wishing there was some way to arrange it so that there was only one return.while (<INFO>) { last if /^\* Menu:/; return %header if /^\037/; } return %header unless defined $_;
Simon Cozens suggested this:
which is better in some ways, but now you have to assign to $_ explicitly, and also it uses do...until which is an unusual construction.do { $_ = <INFO>; return %header if /^\037/ || ! defined $_ } until /^\* Menu:/ ;
I keep feeling like there is something obvious I am missing. Does anyone have any other thoughts?
In reply to Control Flow Puzzle by Dominus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |