in reply to Can this If/Else be condensed into a 1 liner with a trailing If?

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

  • Comment on Re: Can this If/Else be condensed into a 1 liner with a trailing If?
  • Download Code

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

    Shorter still, but (IMHO) just as readable ...

    print "Numbers only please" until <STDIN> =~ /^(\d+)$/; return $1;

        --k.


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
    Isn't exactly the same as: in perl 5.005 and above?

    I remember a time when they *weren't* the same, but I'm pretty sure that they are now.

    -Blake

      Well spotted, and quite correct. When dealing with numbers I tend to step to a higher level of paranoia, simply because zero is a number, but it's not true. This paranoia occasionally wears off onto the code around it. ;)

      Cheers,
      Paul

        Actually, whithin a while (<STDIN>) {...}, the $_ contains the trailing \n. So even though a line might contain a lone zero, it will indeed be "0\n", which is definitely true.

        --bwana147