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

Dear Monks - I am trying to write a piece of code to capture user input?if choice is "y" execute a piece of code, choice is "n" do nothing,anything else ask the user to enter the choice again?Can anyone advise how to do it?

START: print "\nDo you want to continue : "; $choice = <>; chomp ($choice); if ( $choice != "y" && $choice != "n" ) { print "\nERROR:Invalid Choice\n"; goto START; } if($choice == "y") { }

Replies are listed 'Best First'.
Re: Continure when "y" and none for "n"
by wind (Priest) on Apr 28, 2011 at 22:04 UTC

    Something like the following would work:

    my $choice; while (1) { print "\nDo you want to continue : "; chomp($choice = <STDIN>); if ($choice eq "y" || $choice eq "n") { last; } else { print "\nERROR:Invalid Choice\n"; } }

    Note: use eq and ne for string comparison. == and != are used for numerical comparisons

      In the case of user input, a regex is generally better.

      if ($choice ~= /^y(es)?|^no?/i) for example, with case insensitivity and verbose insensitivity.