문제

I'm prompting a user for a correct answer for example:

/> 13 + 7 ?

is it any way of making this output disappear after 2 seconds for example ?

..thanks' for any suggestions

도움이 되었습니까?

해결책 2

Use select on STDIN to see whether there is any input within 2 seconds. If not, overwrite the output with a carriage return (\r) or multiple backspaces (\b).

Proof of concept:

$| = 1;                  # needed because print calls don't always use a newline
$i = int(rand() * 10);
$j = int(rand() * 10);
$k = $i + $j;

print "What is $i + $j ? ";

$rin = '';
vec($rin, fileno(STDIN), 1) = 1;
$n = select $rout=$rin, undef, undef, 2.0;

if ($n) {
    $answer = <STDIN>;
    if ($answer == $k) {
        print "You are right.\n";
    } else {
        print "You are wrong. $i + $j is $k\n";
    }
} else {
    print "\b \b" x 15;
    print "\n\n";
    print "Time's up!\n";
    sleep 1;
}

When you are ready for a more advanced solution, you could probably check out Term::ReadKey (so you don't have to hit Enter after you type in your answer) or something like Curses to exercise more control over writing to arbitrary spots on your terminal.

다른 팁

You're asking for a few things combined, I think:

1) how do you erase a line

2) how do you wait for input for a while and then give up on waiting (ie, a timer)

The following code will do what you want (there are other ways of accomplishing both of the above, but the below shows one way for each of the above tasks):

use strict; use warnings;
use IO::Select;

my $stdin = IO::Select->new();
$stdin->add(\*STDIN);

# always flush
$| = 1;

my $question = "/> 7 + 3 ? ";

print $question;
if ($stdin->can_read(2)) {
    print "you entered: " . <STDIN>;
} else {
    print "\010" x length($question);
    print " " x length($question);
    print "too late\n";
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top