Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I m new to Perl , I need to make a program which will accept only 'y' or 'n' from the user. I want that the user should enter only 1 chacter.(y or n). Is there any way to fulfill this req.
  • Comment on How to restrict the user to enter only 1 character

Replies are listed 'Best First'.
Re: How to restrict the user to enter only 1 character
by tommyw (Hermit) on Oct 29, 2001 at 23:04 UTC
(Ovid) Re: How to restrict the user to enter only 1 character
by Ovid (Cardinal) on Oct 29, 2001 at 23:04 UTC

    Actually, I think it would be more intuitive to allow them to type 'y', 'n', 'yes', 'no', 'Yes', or 'No' and simply test the first character.

    my $answer = <STDIN>; my $first_char = substr $answer, 0, 1; if ( lc $first_char eq 'y' ) { # they answered 'yes' } else { # they answered something else }

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

      Yes, but that would require also pressing Return, which, if I am reading the question right, may not be what the original poster wanted.

      (Actually, I am projecting what I meant, when I myself--oh so many moons ago--asked pretty much the same thing on some forum or another.)

      dmm

      
      You can give a man a fish and feed him for a day ...
      Or, you can teach him to fish and feed him for a lifetime
      
Re: How to restrict the user to enter only 1 character
by jlongino (Parson) on Oct 29, 2001 at 23:03 UTC
    You can probably find what you need by doing a search on: Term::ReadKey

    --Jim

Re: How to restrict the user to enter only 1 character
by broquaint (Abbot) on Oct 29, 2001 at 23:35 UTC
    A function you may want to check out is getc() which reads in the next character from the given filehandle, or STDIN if that isn't specified -
    my $char = getc(); print "you entered $char\n";
    Admittedly this doesn't deliver you a single character at a time, but the docs explain how you can go about achieving that.
    HTH

    broquaint

Re: How to restrict the user to enter only 1 character
by Rich36 (Chaplain) on Oct 29, 2001 at 23:47 UTC
    Mostly the same info, but a different thread from when I asked the same question.... stdin problem...

    Rich36


    There's more than one way to screw it up...