0

我怎么能重写它,以便info在后台运行直到 a$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";
4

2 回答 2

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";
于 2012-11-18T17:52:39.377 回答
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";
于 2012-11-18T22:21:17.820 回答