- 论坛徽章:
- 0
|
本帖最后由 3P主义 于 2012-06-23 12:15 编辑
闭包就是带局部状态的函数,利用闭包,可以传送大量数据给函数。相对于传参方式,主要有以下两个优点:
1. 传送的数据量大。
2. 灵活,能突破参数个数的限制。
上述的优点2在回调代码中更明显,因为回调函数接受的参数都已确定了,不能再传递额外的参数。
以下用 AnyEvent::HTTP 演示闭包的使用,代码中一共有 1000 个关键词要查询,创建了 $cocurrent 个回调函数,每个回调函数都引用着外部的 @words 和 $word ,注意回调函数是怎么再次回调自身的- #!/usr/bin/perl
- use strict;
- use warnings;
- use AnyEvent;
- use AnyEvent::HTTP;
- my $cocurrent = 100; # 并发数
- my @words = map { "keyword" . $_ } (1 .. 1000); # 待查询的关键词
- my $cv = AnyEvent->condvar;
- my @c = splice(@words, 0, $cocurrent);
- foreach my $word (@c) { # 同时创建 $cocurrent 个请求
- $cv->begin();
- my $cb;
- $cb = sub {
- my ($content, $hdr) = @_;
- print "Search: $word\tStatus: ", $hdr->{Status}, "\n";
- $cv->end();
- if (defined ($word = shift(@words))) {
- $cv->begin();
- http_get("http://www.baidu.com/s?wd=${word}", $cb);
- }
- };
- http_get("http://www.baidu.com/s?wd=${word}", $cb);
- }
- $cv->recv();
复制代码 以上代码,每一个请求返回时,会重新创建一个新请求,并发数一直控制在 $cocurrent 个,工作良好。 |
|