Dominus has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE: Control Flow Puzzle
by japhy (Canon) on Nov 16, 2000 at 02:34 UTC | |
by Dominus (Parson) on Nov 16, 2000 at 02:46 UTC | |
|
RE: Control Flow Puzzle
by merlyn (Sage) on Nov 16, 2000 at 02:29 UTC | |
by Dominus (Parson) on Nov 16, 2000 at 02:34 UTC | |
by merlyn (Sage) on Nov 16, 2000 at 03:18 UTC | |
by jeroenes (Priest) on Nov 16, 2000 at 14:45 UTC | |
|
(Ovid) Re: Control Flow Puzzle
by Ovid (Cardinal) on Nov 16, 2000 at 02:40 UTC | |
|
Re: Control Flow Puzzle
by runrig (Abbot) on Nov 16, 2000 at 03:06 UTC | |
|
Re: Control Flow Puzzle
by Dominus (Parson) on Nov 30, 2000 at 06:50 UTC | |
by tilly (Archbishop) on Nov 30, 2000 at 07:15 UTC | |
by Dominus (Parson) on Nov 30, 2000 at 17:38 UTC | |
by tilly (Archbishop) on Nov 30, 2000 at 18:19 UTC | |
by zigster (Hermit) on Nov 30, 2000 at 18:05 UTC | |
by Jonathan (Curate) on Dec 01, 2000 at 13:07 UTC |