One way you can get code to do what you want would be with:

#!/usr/bin/perl use strict; use warnings; print "\nPick a letter between a and d.\n"; chomp(my $reply = <STDIN>); while ($reply !~ /^[a-d]$/i) { print "Please enter only a letter between a and d.\n"; chomp($reply = <STDIN>); }

This code will stay in that while loop until it gets an acceptable response. A couple notes on how it works:

  1. Note the use strict;use warnings at the top of the script. If you are not familiar with these, I would suggest you become so, since they can save you a good bit of debugging headache.
  2. In order to check the input, I use a regular expression. The pattern starts at the beginning of the expression (^), matches one character between a and d inclusive ([a-d]) and then must stop at the end of the expression ($). The modified i makes the match case insensitive. The binding operator !~ is the 'not-matching' operator, so if the contents of $reply do not match the pattern, you stay in the while loop. See perlre and perlretut for info on regular expressions.
  3. In your original code, you use the scalar operator ne on a list. This puts the list in scalar context and hence returns the length of the list, not a comparison against elements. You would only exit, therefore, when $reply was '4'.

Hope this clears things up. Welcome to the monastery.


In reply to Re: do-while loop by kennethk
in thread do-while loop by irvson

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.