我想用 perl 编写一个脚本,为一个变量定义一个值,比如说“10”。 然后,它会要求用户通过 STDIN 输入该变量的值。 如果用户在固定的 TIME INTERVAL 内输入值,然后取该值,否则通过取默认值 10 继续程序。
我不知道该怎么做。我想到了这样的事情.. $t=120(120 秒) 如果用户输入某个值,则每秒减少“$t”的值 然后退出循环,继续,否则当$t变为0时,取默认值继续。 但是,我不知道如何在询问用户输入的同时随时间减少变量的值。
我可以这样做,随着时间的推移减少变量的值,但在此期间,我无法接受输入。
最佳答案
这是一个简单的示例,说明您可以如何处理警报信号。
use strict;
use warnings;
my $input = eval {
my $tmp;
# this sub will be called after the timeout set by the alarm below
local $SIG{ALRM} = sub {
print "timeout - using default value 10\n";
$tmp = 10;
};
print "enter input: ";
alarm 10; # wait for 10 secs
$tmp = <>;
alarm 0; # turn off alarm if we got input within 10 secs
$tmp;
};
print "the value is: $input\n";
关于perl - 随时间减少变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11256365/