Oh good, I'm glad you posted this. I had to take a phone-call while it was being discussed on the chatterbox, and when I came back the conversation had cleared.

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:

while (defined($_ = <STDIN>)) { print "Numbers only please" and next unless (/^\s*(\d+)\s*$/); return $1; } die "urk! Out of input.\n";
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.

It's not a single line, but it probably does what you want, and is shorter than the original code.

Cheers,
Paul


In reply to Re: Can this If/Else be condensed into a 1 liner with a trailing If? by pjf
in thread Can this If/Else be condensed into a 1 liner with a trailing If? by jerrygarciuh

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.