我怎样才能重写这一点,以便info
在后台运行,直到$aw
等于result
?
#!/usr/bin/env perl
use 5.12.0;
use warnings;
use Term::ReadLine;
my $term = Term::ReadLine->new( 'something' );
$term->ornaments( 0 );
sub info {
# in the real script this runs some computations instead of the sleep
# and returns some information.
my ( $time ) = @_;
sleep $time;
return $time * 2;
}
my $value_returned_by_info = info( 10 ); # run this in the background
my $aw;
$aw = $term->readline( 'User input: ' );
if ( $aw eq 'result' ) {
# if info() is still running in the background:
# wait until info() returns because "$value_returned_by_info" is needed.
say $value_returned_by_info;
}
else {
# if info() is still running in the background:
# let info() in the background because "$value_returned_by_info" is not needed here.
say $aw;
}
$aw = $term->readline( 'User input: ' );
if ( $aw eq 'result' ) {
# if info() is still running in the background:
# wait until info() returns because "$value_returned_by_info" is needed.
say $value_returned_by_info;
}
else {
# if info() is still running in the background:
# let info() in the background because "$value_returned_by_info" is not needed here.
say $aw;
}
$aw = $term->readline( 'User input: ' );
if ( $aw eq 'result' ) {
# if info() is still running in the background:
# wait until info() returns because "$value_returned_by_info" is needed.
say $value_returned_by_info;
}
else {
# if info() is still running in the background:
# let info() in the background because "$value_returned_by_info" is not needed here.
say $aw;
}
say "End";
答案 0 :(得分:0)
我同意user5402。提到在后台运行和睡眠信息功能引发了很多问题。
我想知道当给定的输入不正确时,你是否正在寻找一种更加整洁的方式来重新提示输入。如果是这种情况,那么IO :: Prompter模块可能适合您。
#!/usr/bin/env perl
use 5.10.0;
use strict;
use warnings;
use IO::Prompter;
sub info {
my ($time) = @_;
sleep $time;
return $time * 2;
}
my $expect = info(10);
my $aw;
PROMPT:
{
$aw = IO::Prompter::prompt( 'Enter number', -i );
if ( $aw eq $expect ) {
say "$aw :)";
}
else {
say "$aw :(";
redo PROMPT;
}
}
say "End";
答案 1 :(得分:0)
如果info
可以在单独的流程中运行,那么您可以使用fork
。否则你将不得不使用perl的线程版本。
使用fork
:
sub start_info {
my @params = @_;
my $pipe;
my $pid = open($pipe, "-|");
if (!$pid) {
# this code will run in a sub-process
# compute $result from @params
# and print result to STDOUT
sleep(10);
my $result = "p = $params[0] - pid $$";
print $result;
exit(0);
};
my $r;
return sub {
return $r if defined($r);
$r = <$pipe>; # read a single line
waitpid $pid, 0;
$r;
};
}
sub prompt {
print "Hit return: ";
<STDIN>;
}
my $info1 = start_info(4);
prompt();
print "result = ", $info1->(), "\n";
my $info2 = start_info(30);
prompt();
print "result = ", $info2->(), "\n";