问题描述:

I'm a total perl noob and hope this question isn't too stupid!

I'm attempting to write a hangman style game and got it all to work except that for some reason the STDIN seems to execute before the rest of the while loop - so I'm forced to input all of my letter guesses before anything is printed out

while()

{

foreach $letter (@currentword)

{

print "$letter";

}

print "\n";

print "Guess a letter: \n";

chomp($guess = <STDIN>);

$guess=lc(substr($guess,0,1));

if ( $randword =~ /($guess)+/i )

{

print "Correct!\n";

for ($index=0; $index<$wordlength; $index++)

{

if ($wordarray[$index] eq $guess)

{

$currentword[$index]=$wordarray[$index];

}

}

}

else

{

print "Incorrect! try again\n";

}

$guesses -= 1;

last if $guesses < 1;

$finalword = join("",@currentword);

last if ($finalword eq $randword);

}

网友答案:

Your STDOUT must be attached to something other than a terminal, causing block buffering to be used instead of line buffering. Try adding

$| = 1;

(I thought reading from STDIN caused STDOUT to be flushed, though.)

相关阅读:
Top