perl 如何使任何事件“连续”?

uelo1irk  于 2023-03-03  发布在  Perl
关注(0)|答案(2)|浏览(153)

我想尝试混合AnyEvent和Coro。
有没有办法让BEGIN和END之间的三条线更优雅/浓缩?

use AnyEvent::HTTP;
use Coro;

async {
  _
  # BEGIN
  my $READY = AnyEvent->condvar;
  my $guard = http_request( GET => $url, $READY );
  my ($data, $hHeaders ) = $READY->recv;
  # END
  …
}
    • 警告**:man AnyEventCoro集成建议了略微不同的方式,但总体思路保持不变(接受回复后添加注解)。
AnyEvent::HTTP::http_get "url", Coro::rouse_cb;
my ($body, $hdr) = Coro::rouse_wait;
p4rjhz4m

p4rjhz4m1#

潜艇这就是潜艇的作用。

sub sync {
   my $sub = shift;
   $sub = \&$sub;   # Make `strict refs` happy.
   my $done = AnyEvent->condvar;
   my $guard = $sub->( @_, $done );
   return $done->recv;
}

my ( $data, $headers ) = sync \&http_request, GET => $url;
  # -or-
my ( $data, $headers ) = sync http_request => GET => $url;

use Sub::Name qw( sub_name );

sub build_sync(_) {
   my $wrapped_sub_name = shift;
   my $wrapped_sub = \&$wrapped_sub_name;

   my $sub_name = $wrapped_sub_name . '_sync';
   my $sub = sub_name $sub_name => sub {
      my $done = AnyEvent->condvar;
      my $guard = $wrapped_sub->( @_, $done );
      return $done->recv;
   };

   no strict qw( refs );
   *$sub_name = $sub;
}

build_sync for qw( http_request ... );

my ( $data, $headers ) = http_request_sync( GET => $url );
h79rfbju

h79rfbju2#

我们可以使用以下方法:

sub SYNC (\&@) {
  my $sub = shift @_;
  my $READY =  AnyEvent->condvar;
  my $guard = &$sub( @_, $READY);
  return $READY->recv;
}

my ($data, $hHeaders ) = SYNC &http_request, GET => $url;

相关问题