我用perl编写了一个head/tails脚本,希望它能运行不止一次



我知道有一个简单的单行或命令会让它一遍又一遍地运行,直到我杀死它,有人能给我看吗?

#!/usr/bin/perl
print "Content-type: text/htmlnn";
print "Please type in either heads or tails: ";
$answer = <STDIN>;
chomp $answer;
while ( $answer ne "heads" and $answer ne "tails" ) {
    print "I asked you to type heads or tails. Please do so: ";
    $answer = <STDIN>;
    chomp $answer;
}
print "Thanks. You chose $answer.n";
print "Hit enter key to continue: ";
$_ = <STDIN>;
if ( $answer eq "heads" ) {
    print "HEADS! you WON!n";
} else {
    print "TAILS?! you lost. Try again!n";
}

是代码。我希望它在初次运行后一次又一次地询问

只需将代码的主要部分包装在while循环中。

#!/usr/bin/perl
print "Content-type: text/htmlnn";
while (1) {
    print "Please type in either heads or tails: ";
    $answer = <STDIN>;
    chomp $answer;
    while ( $answer ne "heads" and $answer ne "tails" ) { 
        print "I asked you to type heads or tails. Please do so: ";
        $answer = <STDIN>;
        chomp $answer;
    }   
    print "Thanks. You chose $answer.n";
    print "Hit enter key to continue: ";
    $_ = <STDIN>;
    if ( $answer eq "heads" ) { 
        print "HEADS! you WON!n";
    } else {
        print "TAILS?! you lost. Try again!n";
    }   
}   

这里有很多假设,但bash shell中的"一行或命令"可以用完成

$ while true; do perl yourscript.pl; done

kbenson可以将代码包围在无限循环中,这是正确的。做这件事的一个稍微优雅的方法是制作一个播放一轮的函数,然后围绕该函数调用进行无限循环。我在这里再使用一些技巧,其中一些可能对你来说是新的,如果你不明白什么,请问。我也同意cjm的观点,我不确定为什么会有内容类型,所以我把它省略了。

#!/usr/bin/env perl
use strict;
use warnings;
while (1) {
  play_round();
  print "Would you like to play again?: ";
  my $answer = <STDIN>;
  if ($answer =~ /no/i) {
    print "Thanks for playing!n";
    last; #last ends the loop, since thats the last thing exit would work too
  }
}
sub play_round {
    print "Please type in either heads or tails: ";
    my $answer = <STDIN>;
    chomp $answer;
    while ( $answer ne "heads" and $answer ne "tails" ) { 
        print "I asked you to type heads or tails. Please do so: ";
        $answer = <STDIN>;
        chomp $answer;
    }   
    print "Thanks. You chose $answer. Now I'll flip.n";
    sleep 1;
    my @coin = ('heads', 'tails');
    my $side = $coin[int rand(2)];
    print "And its ... $side! ";
    if ( $answer eq $side ) { 
        print "You WON!n";
    } else {
        print "Sorry, you lost. Try again!n";
    }   
}   

最新更新