4
我已經在幾個Perl腳本上卸載了一些維護任務。其中一個要求是並行下載幾十個文件(HTTP)。我在CPAN上尋找最簡單的解決方案,並找到了稱爲IO::Lambda::HTTP的模塊。IO :: Perl中的Lambda
不幸的是,我對函數式編程(和初學者級別的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);
可有人告訴我(例如限制N個實例)什麼樣的拉姆達代碼是這樣給出了上述約束的例子?
另外,什麼是開始學習函數式編程的最好方法?這對我來說似乎完全陌生。
同意,這是沉重的東西。對於Perl和FP掌握的初學者來說,IO :: Lambda方法可能會非常令人沮喪。 AnyEvent :: HTTP看起來可用,儘管它仍然需要一些工作來限制並行請求的數量。 – ivancho 2010-12-07 10:00:38