I don't often use a do-while loop, but when I was writing my Animals program, I found this to be a useful little trick for interactive input that needs a certain letter.
do { print "\nDid I guess your animal?\n\n"; } while ($answer=<STDIN>) !~ /^[YN]/i; ## OR do { print "\nDo you want to <P>lay again or <Q>uit?\n\n"; } while ($answer=<STDIN>) !~ /^[PQ]/i;
The three newlines help to clear out the users input and make a nicer looking response if they fail to answer with a correct letter. Since $answer has already been set, after the loop you can say:
if ($answer =~ /^P/i) { ## Code for P here } ## Add some elsifs if > 2 choices else { ## No need to check the final letter ## Code for Q here }

Replies are listed 'Best First'.
RE: Do/while correct answer loop
by merlyn (Sage) on May 12, 2000 at 19:49 UTC
    I tend to avoid the do {...} while $cond loop because it's not a real loop. You can't use next/last/redo with it. As I said in this week's poll, I use a naked block with last and redo:
    { stuff more stuff last if $cond; # middle exit still more stuff again more stuff redo if $cond; # repeat as long as $cond is true }
    This way you can name the loop (for multiple break-outs). If you want next OUTERLOOP to work, you merely next to add additional continue block:
    OUTERLOOP: { blah while ($foo) { blah next OUTERLOOP if $cond; blah } blah } continue { redo if $cond; }
    Naked blocks are fun!

    -- Randal L. Schwartz, Perl hacker

      Yes, but when else am I going to use poor old "do/while?" :)

      I admit, the bare block does look better:

      { print "\nDo you want to <P>lay again or <Q>uit?\n\n"; ($answer=<STDIN>) =~ /^[PQ]/i or redo; }