简体   繁体   中英

infinite input loop until user quits in Perl

How to take a infinite input loop until he quits in Perl as i am unable to quit from the code properly even after entering quit or q. Your help is highly appreciated.

do
 {
 &ipdiscover;
 print "enter q or quit to exit";
  my $input=<>;
  chomp($input);
  if($input=="quit")
  exit;
}until(($input eq "quit")||($input eq "q"));

&ipdiscover – never call functions like that, except when you know about all the side effects. If in doubt, do ipdiscover() .

Do not compare strings with the == operator: That coerces the arguments to numbers. If it doesn't look like a number, you get zero. So $input == "quit" is very likely true for most $input s.

However, the if statement is defined in terms of blocks, not in terms of statements (as in C). Therefore, you have to do

if ($input eq "quit") {
  exit;
}

Or a shorthand: exit if $input eq "quit"; . But why would you want to do that? exit terminates the whole program.

On the other hand, until(($input eq "quit")||($input eq "q")) is a correct termination condition, and would work as expected once you fix the scope of $input .

I think you should rather do the following, because this handles the end of input better (eg on Linux: a Ctrl-D, Windows; Ctrl-Z):

use strict; use warnings; # put this at the top of every program!

while(defined(my $answer = prompt("type q or quit to exit: "))) {
  last if $answer eq "q"
       or $answer eq "quit"
}

sub prompt {
  my ($challenge) = @_;
  local $| = 1;  # set autoflush;
  print $challenge;
  chomp( my $answer = <STDIN> // return undef);
  return $answer;
}

You can leave a loop by saying this was the last iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM