Subscribed unsubscribe Subscribe Subscribe

Kentaro Kuribayashi's blog

Software Engineering, Management, Books, and Daily Journal.

AnyEventでtail -f

AnyEventの練習をしてみようってんで、とりあえずtail -fぽいのを書いてみる。こんなんでいいんだろうか……。よくわからない。

#!/usr/bin/env perl
use strict;
use warnings;
use AnyEvent;
use AnyEvent::Handle;

$| = 1;

my $file = shift or die qq{usage: $0 filename};
open my $fh, '<', $file or die qq{can't open file: $file};
my $cv = AE::cv;
my $handle = create_handle();

sub create_handle {
    new AnyEvent::Handle
        fh => $fh,
        on_error => sub {
            my ($handle, $fatal, $message) = @_;
            $handle->destroy;
            undef $handle;
            $cv->send("$fatal: $message");
        },
        on_eof => sub {
            $handle->destroy;
            undef $handle;
            $handle = create_handle();
        },
        on_read => sub {
            my $handle = shift;
            $handle->push_read(line => sub {
                my ($handle, $line) = @_;
                print "$line\n";
            })
        };
}

warn $cv->recv;