Coro で WWW::Mechanize を使ってみる

#!/usr/bin/env perl
use strict;
use warnings;
use Coro;
use Coro::LWP;
use Data::Dumper;
use WWW::Mechanize;

my @coros = ();
my @urls  = qw|https://twitter.com/ https://www.pinterest.com/ http://www.apple.com/|;

foreach my $url (@urls) {
    push @coros, async {
        my $mech = WWW::Mechanize->new;
        printf("Loaded: %s\n", $url);

        my $res = $mech->get($url);

        printf("Got %s title is %s\n", $url, $mech->title);
    };
}

$_->join for @coros;

実行時の出力例。出力順は実行の度に異なる。

Loaded: https://twitter.com/
Loaded: https://www.pinterest.com/
Loaded: http://www.apple.com/
Got http://www.apple.com/ title is Apple
Got https://twitter.com/ title is Twitter
Got https://www.pinterest.com/ title is Pinterest

実際に利用する場合は、エラー処理をどう実装するか考えておく必要がある。