“Use of uninitialized value $_” warning with a Mojo::UserAgent non-blocking request

孤街醉人 提交于 2019-12-13 04:22:56

问题


I am trying to make a non-blocking request with Mojo::UserAgent but when I run the code below I get

Use of uninitialized value $_ in concatenation (.) or string

on the print line.

How can I access $_ inside the callback?

my $ua = Mojo::UserAgent->new();

my @ids = qw( id1  id2 id3 );

foreach ( @ids ) {

    my $res = $ua->get('http://my_site/rest/id/'.$_.'.json' => sub {
        my ($ua, $res) = @_;
        print "$_ => " . $res->result->json('/net/id/desc'), "\n";
    });
}

Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

回答1:


$_ is a special kind of variable where the value depends on the context. Inside the foreach (@ip) context it is set as an alias of specific item in the @ip array. But, the callback for $ua->get(...) gets not executed within the foreach (@ip) context and thus $_ no longer is an alias into the @ip array.

Instead of using this special variable you need to use a normal variable scoped inside the foreach (@ip) loop, so that it can be bound to the subroutine (see also What's a closure in perlfaq7):

foreach (@ip) {
   my $THIS_IS_A_NORMAL_VARIABLE = $_;
   my $res= $ua->get( ...  => sub {
      my ($ua, $res) = @_;
      print  "$THIS_IS_A_NORMAL_VARIABLE =>" . $res->result->json('/net/id/desc'),"\n";
   });
}


来源:https://stackoverflow.com/questions/52243566/use-of-uninitialized-value-warning-with-a-mojouseragent-non-blocking-requ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!