我知道有一个简单的单行或命令让它一遍又一遍地运行直到我杀了它,有人能告诉我吗?
#!/usr/bin/perl
print "Content-type: text/html\n\n";
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";
}
是代码吗?我希望它在初次运行后一次又一次地询问
答案 0 :(得分:1)
将代码的主要部分包装在while循环中。
#!/usr/bin/perl
print "Content-type: text/html\n\n";
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";
}
}
答案 1 :(得分:1)
这里有很多假设,但是来自bash shell的“单行或命令”可以通过以下方式完成:
$ while true; do perl yourscript.pl; done
答案 2 :(得分:1)
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";
}
}