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

I have a part of my script that works but wondering how I can put this in a 'while' loop and do the same thing?
do { print "Enter Yes or No \n"; chomp($input = <>); if ($input eq 'yes') { print "Yes entered for system.\n"; } elsif($input eq 'no') { print "No entered for system.\n"; } } until ($input =~ /^yes$/ or $input =~ /^no$/);

Replies are listed 'Best First'.
Re: While loop
by particle (Vicar) on May 14, 2002 at 18:16 UTC
    as a one-liner:

    $ perl -Mstrict -w -e'while(1){ chomp( my $i = <STDIN>); $i eq "yes" & +& print "yes" && last; $i eq "no" && print "no" && last }'
    as legible code:

    #!/usr/bin/perl -w use strict; $|++; while(1) { chomp( my $i = <STDIN> ); if( $i eq 'yes' ) { print "Yes entered for system.\n"; last } if( $i eq 'no' ) { print "No entered for system.\n"; last } }
    it's an infinite loop--the only way to exit is to enter a valid response.

    aw, heck, there's more than one way to do it...

    my $response = qr/^(yes|no)$/; while( chomp( $_ = <STDIN> ) ) { /$response/ and print "$1 entered for system.$/" and last }

    ~Particle *accelerates*

Re: While loop
by vladb (Vicar) on May 14, 2002 at 18:12 UTC
    You have to change a minor piece of your code, that is replace 'until' with 'while' ;-).

    Just like so..
    do { print "Enter Yes or No \n"; chomp($input = <>); if ($input eq 'yes') { print "Yes entered for system.\n"; } elsif($input eq 'no') { print "No entered for system.\n"; } } while ($input =~ /^yes$/ or $input =~ /^no$/);


    $"=q;grep;;$,=q"grep";for(`find . -name ".saves*~"`){s;$/;;;/(.*-(\d+) +-.*)$/;$_=["ps -e -o pid | "," $2 | "," -v "," "];`@$_`?{print"+ $1"} +:{print"- $1"}&&`rm $1`;print"\n";}
      Shouldn't the
      while ($input =~ /^yes$/ or $input =~ /^no$/);
      actually be
      while ($input !~ /^yes$/ or $input !~ /^no$/);
      ?
      Who says that programmers can't work in the Marketing Department?
      Or is that who says that Marketing people can't program?
      Thanks for all answers.
Re: While loop
by thelenm (Vicar) on May 14, 2002 at 18:15 UTC
    You can use last to jump out the loop when you get the input you want:
    while(defined($input = <>))) { chomp $input; if ($input eq 'yes') { print "Yes entered for system.\n"; last; } elsif ($input eq 'no') { print "No entered for system.\n"; last; } }
Re: While loop
by mephit (Scribe) on May 14, 2002 at 19:59 UTC
    my $input = ''; until (($input =~ /^yes/i) or ($input =~ /^no/i)) { print "Please Enter Yes or No: \n"; chomp($input = <>); printf "'%s' entered for system\n", $input;
    That works. It'll echo every value entered, which you didn't ask for, but it will also prompt for "yes" or "no" after every 'incorrect' input. Why patterns instead of eq? Easier to customize, IMO, in case you want to allow for different case (with the /i, as above), or just allow for 'y' or 'n,' or whatever. HTH