io :: lambda in perl
-
09-10-2019 - |
题
我已经在几个Perl脚本上卸载了一些维护任务。一个要求之一是并行下载几十个文件(HTTP)。我去查找CPAN寻求最简单的解决方案,发现了这个模块称为 io :: lambda :: http.
不幸的是,我绝对没有功能编程(和初学者级的Perl经验)的经验,因此,尽管我看到所有示例的作品都可以记录下来,但我无法真正修改它们以适应我的需求。
例如,该模块随附的示例:
#!/usr/bin/perl
# $Id: parallel.pl,v 1.7 2008/05/06 20:41:33 dk Exp $
#
# This example fetches two pages in parallel, one with http/1.0 another with
# http/1.1 . The idea is to demonstrate three different ways of doing so, by
# using object API, and explicit and implicit loop unrolling
#
use lib qw(./lib);
use HTTP::Request;
use IO::Lambda qw(:lambda);
use IO::Lambda::HTTP qw(http_request);
use LWP::ConnCache;
my $a = HTTP::Request-> new(
GET => "http://www.perl.com/",
);
$a-> protocol('HTTP/1.1');
$a-> headers-> header( Host => $a-> uri-> host);
my @chain = (
$a,
HTTP::Request-> new(GET => "http://www.perl.com/"),
);
sub report
{
my ( $result) = @_;
if ( ref($result) and ref($result) eq 'HTTP::Response') {
print "good:", length($result-> content), "\n";
} else {
print "bad:$result\n";
}
# print $result-> content;
}
my $style;
#$style = 'object';
#$style = 'explicit';
$style = 'implicit';
# $IO::Lambda::DEBUG++; # uncomment this to see that it indeed goes parallel
if ( $style eq 'object') {
## object API, all references and bindings are explicit
sub handle {
shift;
report(@_);
}
my $master = IO::Lambda-> new;
for ( @chain) {
my $lambda = IO::Lambda::HTTP-> new( $_ );
$master-> watch_lambda( $lambda, \&handle);
}
run IO::Lambda;
} elsif ( $style eq 'explicit') {
#
# Functional API, based on context() calls. context is
# $obj and whatever arguments the current call needs, a RPN of sorts.
# The context though is not stack in this analogy, because it stays
# as is in the callback
#
# Explicit loop unrolling - we know that we have exactly 2 steps
# It's not practical in this case, but it is when a (network) protocol
# relies on precise series of reads and writes
this lambda {
context $chain[0];
http_request \&report;
context $chain[1];
http_request \&report;
};
this-> wait;
} else {
# implicit loop - we don't know how many states we need
#
# also, use 'tail'
this lambda {
context map { IO::Lambda::HTTP-> new( $_, async_dns => 1 ) } @chain;
tails { report $_ for @_ };
};
this-> wait;
}
如广告宣传的作品,但我不能为自己的一生弄清楚如何修改“对象”或“隐式”示例,以限于n个并行实例,例如IO :: lambda的简介:
# http://search.cpan.org/~karasik/IO-Lambda/lib/IO/Lambda.pm
# crawl for all urls in parallel, but keep 10 parallel connections max
print par(10)-> wait(map { http($_) } @hosts);
有人可以向我展示一个示例,说明lambda代码给定上述约束(例如n实例的限制)?
另外,开始学习功能编程的最佳方法是什么?对我来说似乎完全是陌生的。
解决方案
例如,除了IO :: Lambda以外的其他选择,例如 AnyEvent :: HTTP. 。看 以前的问题.
即使我熟悉功能编程,上面的IO :: lambda示例代码对我来说似乎很难理解。
不隶属于 StackOverflow