Snippets

Brian Medley Example to try and show a read event oddity

Created by Brian Medley last modified
package Joy;

use IO::File;

use Mojo::Base 'Mojo::EventEmitter';

use Mojo::IOLoop;

our $VERSION = '0.02';

has 'ioloop' => sub { Mojo::IOLoop->singleton };
has 'file';
has 'leftovers';
has 'whence';
has 'size';

package main;

use IO::File;

    my $self = Joy->new;

    $self->{file} = "tail.me";

    my $fh = IO::File->new();
    unless ($fh->open($self->file, "r")) {
        $self->emit(error => sprintf("Can't open %s: $!", $self->file));
        return;
    }

    $fh->autoflush(1);
    $fh->seek(0, SEEK_END);

    my $reactor = $self->ioloop->reactor;
    $reactor->io($fh =>
        sub {
            my ($ret, $buf);

            while ($ret = $fh->read($buf, 1024)) {
                unless ($ret) {
                    $fh->clearerr if $fh->error;
                    last;
                }

                while ($buf =~ m/\G(.*?)(\x0d?\x0a)/g) {
                    print("$1$2");
                }

                print("$1\n\n") if $buf =~ m/\G(.{1,-})$/g;
            }
        }
    )->watch($fh, 1, 0);

$self->ioloop->start unless $self->ioloop->is_running;

1;

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.