Piping with AnyEvent::Handle
Marc Lehmann
schmorp at schmorp.de
Sat Mar 19 12:52:35 CET 2011
On Wed, Mar 16, 2011 at 09:56:22AM +0100, yon ar c'hall <yon.ar.chall at gmail.com> wrote:
> > my $aer; $aer = new AnyEvent::Handle fh => $r;
> > $aer->push_read(line => sub {
> > my (undef, $line) = @_;
> > print "<$line>\n";
> > undef $aer; # keep $aer from being destructed until here
> > });
> >
>
> scope) when doing event programming. Some remarks : instead of "undef
> $aer;", we could have just write "$aer;" (if we want to read more than one
> line). If I understand well, it's just a way of keeping a reference to the
> variable "$aer", so that Perl does not automatically destroy it. Also, the
Yes, it would have the same effect in this simple example, but there is an
important difference in more complex situations: the undef destroys your
reference to the handle, or in other words, it signals perl that you don't
want to have the object any longer.
Just referencing it does no such thing: in an on_timeout callback for example,
this would not destroy your reference, as unlike the pushed handler, the
on_timeout handler doesn't immediately get destroyed, so keeps referencing
$aer.
Likewise in the case of multiple callbacks (and you really should have an
on_error callback :).
In this case
> could have simply code "my $aer = new ...").
Yes, because you don't pass an on_error handler and don't reference it in
there, which is highly recommended :)
> > So in general, once you created your handle object, it should become *the
> > handle*, i.e. you should not keep the original fh around.
>
> Here, I don't see how to implement this. Could you please explain further
> (based on the present pipe example) ?
Well, basically, as soon as you have created the handle, throw away the
fh and only use the handle.
It's the same with buffered perl handles - once you have created one from
an fd and it did read some data, it will be thrown away when you create
another handle form the same fd.
If you just want to read one line from the pipe (and there are multiple),
then the only way is to read byte-by-byte, which is of coruse very slow.
If you know there is only a single line in the pipe, and it's small enough
(<= 512 bytes), you can also just sysread it in one go, relying on pipe
atomicity.
--
The choice of a Deliantra, the free code+content MORPG
-----==- _GNU_ http://www.deliantra.net
----==-- _ generation
---==---(_)__ __ ____ __ Marc Lehmann
--==---/ / _ \/ // /\ \/ / schmorp at schmorp.de
-=====/_/_//_/\_,_/ /_/\_\
More information about the anyevent
mailing list