什么是事件編程?
舉個(gè)簡(jiǎn)單的例子,你瀏覽網(wǎng)頁的時(shí)候,你點(diǎn)擊一個(gè)圖片,蹭的彈出一個(gè)東西,你不點(diǎn),那就在那里,等待一個(gè)人來點(diǎn)它。如果你寫過js,其實(shí)就是,你注冊(cè)了很多的時(shí)間比如click,dbclick,keybord,submit等,那么瀏覽器就起到幫我們?nèi)ケO(jiān)聽這些事件的發(fā)生(Loop)。當(dāng)有對(duì)應(yīng)的事件發(fā)生的時(shí)候,我們也一般也設(shè)置了callback,比如onclick,onsubmit等,去響應(yīng)這些事件,這基本就是事件編程的一個(gè)縮影了。
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的一部分其實(shí)像javascript的setInterval :
代碼如下:
#!/usr/bin/perl
use 5.016;
use AnyEvent ;
my $cv = AnyEvent->condvar ;
my $w = AnyEvent->timer(
after => 0 , #多少秒之后觸發(fā)事件
interval => 2 , #多少秒觸發(fā)事件
cb => sub {
say AnyEvent->time ," ",AnyEvent->now ;
}
);
$cv->recv;
signal watcher
前面我們?cè)诘奈恼轮袑懙搅藀erl中對(duì)于信號(hào)的處理 《perl信號(hào)處理簡(jiǎn)單學(xué)習(xí)》,這里主要是AnyEvent中對(duì)于這些事件的處理。
代碼如下:
#!/usr/bin/perl
use 5.016;
use AnyEvent ;
#say for keys %SIG; 看一下又多少信號(hào)
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在空閑的時(shí)候做些什么呢?
代碼如下:
#!/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;
更多信息請(qǐng)查看IT技術(shù)專欄