These days I looked at Perl's event programming framework Anyevent, focusing on a few articles:
http://search.cpan.org/~mlehmann/AnyEvent-7.05/lib/AnyEvent.pm
Http://search.cpan.org/~mlehmann/AnyEvent-7.05/lib/AnyEvent/Intro.pod
Http://www.jb51.net/article/55278.htm
1, what is event programming?
As a simple example, when you browse the Web, you click on a picture, rub a pop-up thing, you do not point, that is there, waiting for a person to point it. If you have written JS, in fact, you register a lot of time such as Click,dbclick,keybord,submit, then the browser to help us to monitor the occurrence of these events (Loop). When there is a corresponding event, we also generally set the callback, such as Onclick,onsubmit, to respond to these events, this is basically a microcosm of event programming.
2. Watcher in Perl anyevent
In the anyevent, there are 5 watcher, io,timer,signal, child, Idle, respectively.
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
Part of the anyevent timer is actually like the setinterval of javascript:
#!/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
In the previous article we wrote about the processing of signals in Perl, "The simple learning of Perl signal processing," which is mainly about the handling of these events in Anyevent.
#!/usr/bin/perl
Use 5.016;
Use anyevent;
#say for Keys%sig; Let's see how many signals.
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
is what if main loop does something in its spare time?
#!/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 a idle watcher, if not already done
$idle _w | | = Anyevent->idle (CB => SUB {
# handle only one line while 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;