perl6 如何获得特定身份的承诺?

perl6 how to get specific identity of promises?

我正尝试在 promises 中编写 3 个回显服务器 运行ning,但我想知道哪个 promise 正在执行回显。有没有办法做到这一点?

no strict;

for 0 .. 2 -> $index {
    @result[$index] = start {
        $myID = $index; 
        say "======> $myID\n";

        my $rsSocket = IO::Socket::INET.new:
            localhost => 'localhost',
            localport => 1234 + $index,
            listen    => 1;

        while $rsSocket.accept -> $rsConnection {
            say "Promise $myID accepted connection";
            while $rsConnection.recv -> $stuff {
                say "promise $myID Echoing $stuff";
                $rsConnection.print($stuff);
            }
            $rsConnection.close;
        }
    }
}

await @result;

echo 服务器 运行 ok;用 "nc";

测试

问题是在创建 promise 后 $myID 变成了 2,我无法分辨哪个 promise 正在执行当前回显。似乎 $myID 被所有的承诺所使用;有没有办法创建特定于单个承诺的变量?

这是你 "lose" 与 no strict 一起做的事情之一。

你需要的是词法范围。使用 my 将在每次输入块 ({ ... }) 时为您提供不同的变量。

如果你这样做:

for 0 .. 2 -> $index {
    @result[$index] = start {
        my $myID = $index; 

然后 $myID 将是 start 块的本地,每次调用该块时,它都会记住它的 ID。因此,只要套接字收到数据,您就会获得正确的 ID。

您根本不需要 $myID。您可以只在 promise 中使用 $index 因为它已经被限定在循环块中。这是一个有效的修改(..with strict on):

my @result = do for 0 .. 2 -> $index {
    start {
        say "======> $index\n";

        my $rsSocket = IO::Socket::INET.new:
            localhost => 'localhost',
            localport => 1234 + $index,
            listen    => 1;

        while $rsSocket.accept -> $rsConnection {
            say "Promise $index accepted connection";
            while $rsConnection.recv -> $stuff {
                say "promise $index Echoing $stuff";
                $rsConnection.print($stuff);
            }
            $rsConnection.close;
        }
    }
}

await @result;

考虑到这一点,我很想指出使用 no strict 似乎非常不必要。它不仅让您对这些奇怪的范围问题持开放态度,而且在您的示例中这样做基本上没有任何好处。

对未修改的代码重新启用 strict 并修复两个编译错误表明总共只节省了四次击键 - 代价是您在此处输入问题时使用了多少键。