in reply to Can this If/Else be condensed into a 1 liner with a trailing If?
Firstly your regexp will match anything which has a digit it in somewhere. This might not be what you want. Perhaps something like /^\s*(\d+)\s*$/ would be better, to require a sequence of digits with possible whitespace on either side. This leaves your number in $1 afterwards.
Secondly, think twice about having your input function call your input function. You could end up with a very large call stack here, killing performance and chewing memory.
I would suggest you use a loop like this:
This keeps reading from STDIN until we get a number (in which case we return it), or we run out of input. Plus there's no recusion involved, which is much better than calling ourselves repeatedly.while (defined($_ = <STDIN>)) { print "Numbers only please" and next unless (/^\s*(\d+)\s*$/); return $1; } die "urk! Out of input.\n";
It's not a single line, but it probably does what you want, and is shorter than the original code.
Cheers,
Paul
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Can this If/Else be condensed into a 1 liner with a trailing If?
by Kanji (Parson) on Oct 02, 2001 at 08:28 UTC | |
|
Re: Re: Can this If/Else be condensed into a 1 liner with a trailing If?
by blakem (Monsignor) on Oct 02, 2001 at 08:05 UTC | |
by pjf (Curate) on Oct 02, 2001 at 08:17 UTC | |
by bwana147 (Pilgrim) on Oct 02, 2001 at 19:08 UTC | |
by Anonymous Monk on Oct 02, 2001 at 21:28 UTC | |
by blakem (Monsignor) on Oct 02, 2001 at 21:46 UTC |