Perl AnyEvent中的watcher实例

2023-12-05 0 753

这几天看了下perl的事件编程框架AnyEvent,重点参考了一下几篇文章:

http://search.cpan.org/~mlehmann/AnyEvent-7.05/lib/AnyEvent.pm

http://search.cpan.org/~mlehmann/AnyEvent-7.05/lib/AnyEvent/Intro.pod

https://www.jb51.net/article/55278.htm

1、什么是事件编程?

举个简单的例子,你浏览网页的时候,你点击一个图片,蹭的弹出一个东西,你不点,那就在那里,等待一个人来点它。如果你写过js,其实就是,你注册了很多的时间比如click,dbclick,keybord,submit等,那么浏览器就起到帮我们去监听这些事件的发生(Loop)。当有对应的事件发生的时候,我们也一般也设置了callback,比如onclick,onsubmit等,去响应这些事件,这基本就是事件编程的一个缩影了。

2、perl AnyEvent中的watcher

在AnyEvent中有5中watcher,分别是IO,timer,signal, child, idle.

2.1 io watcher

复制代码 代码如下:
#!/usr/bin/perl

use AnyEvent;
my $cv = AnyEvent->condvar;

#open my $file , \'<\’ , \’test.txt\’ or die \”$!\” ;
open F , \'<\’ , \’test.txt\’ or die \”$!\” ;
my $io_watcher = AnyEvent->io (
fh => *F,
poll => \’r\’,
cb => sub {
chomp (my $input = sysread F ,my $buf ,1024); # read a line

warn \”read: $buf\\n\” if $input >0 ; # output what has been read
#$cv->send if /quit/ ; # quit program if /quit/i
},
);

$cv->recv; # wait until user enters /quit/i

timer watcher

AnyEvent 的timer的一部分其实像javascript的setInterval :

复制代码 代码如下:
#!/usr/bin/perl

use 5.016;
use AnyEvent ;

my $cv = AnyEvent->condvar ;

my $w = AnyEvent->timer(
after => 0 , #多少秒之后触发事件
interval => 2 , #多少秒触发事件
cb => sub {
say AnyEvent->time ,\” \”,AnyEvent->now ;

}
);

$cv->recv;

signal watcher

前面我们在的文章中写到了perl中对于信号的处理 《perl信号处理简单学习》,这里主要是AnyEvent中对于这些事件的处理。复制代码 代码如下:
#!/usr/bin/perl

use 5.016;
use AnyEvent ;
#say for keys %SIG; 看一下又多少信号
my $cv = AnyEvent->condvar ;

my $w = AnyEvent->signal(
signal => \’INT\’,
cb => sub {
say AnyEvent->time ,\” \”,AnyEvent->now ;
exit 1 ;

}
);

$cv->recv;

child watcher

复制代码 代码如下:
#!/usr/bin/perl
use AnyEvent;
my $done = AnyEvent->condvar;

my $pid = fork or exit 5;

my $w = AnyEvent->child (
pid => $pid,
cb => sub {
my ($pid, $status) = @_;
warn \”pid $pid exited with status $status\”;
$done->send;
},
);

# do something else, then wait for process exit
$done->recv;

idle watcher

就是如果main loop在空闲的时候做些什么呢?

复制代码 代码如下:
#!/usr/bin/perl
use AnyEvent;
my @lines; # read data
my $idle_w;
$cv = AnyEvent->condvar;
my $io_w = AnyEvent->io (fh => \\*STDIN, poll => \’r\’, cb => sub {
push @lines, scalar <STDIN>;

# start an idle watcher, if not already done
$idle_w ||= AnyEvent->idle (cb => sub {
# handle only one line, when there are lines left
if (my $line = shift @lines) {
print \”handled when idle: $line\”;
} else {
# otherwise disable the idle watcher again
undef $idle_w;
}
});
});

$cv->recv;

您可能感兴趣的文章:

  • perl AnyEvent简单介绍和入门知识

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 Perl Perl AnyEvent中的watcher实例 https://www.u-9.cn/jiaoben/perl/100089.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务