in reply to do-while loop

You're misusing the range operator. You probably want while( $reply !~ /^[abcd]$/i );, which is to say, while $reply does not contain the single character of a, b, c, or d, case insensitive.

I don't really love the loop you've chosen either. I think I would be more comfortable with:

prompt; while( <STDIN> ) { chomp; last if /^[a-d]$/i; prompt; } sub prompt { print "\nPick a letter between a and d.\n"; }

The inelegant part is that you have to prompt outside of the loop once, but the more elegant part is that you're actually checking whether or not there IS more input to be read. That way, should STDIN happen to run out of input (for example, in the case of the script being fed an input file instead of keyboard input, it can terminate when it runs out of lines of text to read.


Dave

Replies are listed 'Best First'.
Re^2: do-while loop
by JadeNB (Chaplain) on Nov 04, 2009 at 05:16 UTC
    The inelegant part is that you have to prompt outside of the loop once, but the more elegant part is that you're actually checking whether or not there IS more input to be read. That way, should STDIN happen to run out of input (for example, in the case of the script being fed an input file instead of keyboard input, it can terminate when it runs out of lines of text to read.

    I think that one could strike a balance by using

    do { … } while length $reply and …
    (This quits on empty input; but, then again, the original version provides no non-CTRL-C way to get out of the loop if you don't happen to remember the letters from a to d—so maybe that's a feature.)

    UPDATE: Oops, my original version had while $reply and …, which quits on input 0, which seems incorrect by any measure.