Snippets

Brian Medley Example to try and show a read event oddity

Updated by Brian Medley

File read_event_oddity.pl Modified

  • Ignore whitespace
  • Hide word diff
     }
 
     $fh->autoflush(1);
-    $fh->sysseek(0, SEEK_END);
+    $fh->seek(0, SEEK_END);
 
     my $reactor = $self->ioloop->reactor;
     $reactor->io($fh =>
Updated by Brian Medley

File read_event_oddity.pl Modified

  • Ignore whitespace
  • Hide word diff
         return;
     }
 
-    $fh->autoflush(0);
+    $fh->autoflush(1);
     $fh->sysseek(0, SEEK_END);
 
     my $reactor = $self->ioloop->reactor;
             my ($ret, $buf);
 
             while ($ret = $fh->read($buf, 1024)) {
-                if (0 == $ret) {
-                    $fh->seek(0, SEEK_CUR); # clear eof
-                    last;
-                } elsif (!defined $ret) {
-                    $fh->seek(0, SEEK_CUR); # clear error
+                unless ($ret) {
+                    $fh->clearerr if $fh->error;
                     last;
                 }
 
Created by Brian Medley

File read_event_oddity.pl Added

  • Ignore whitespace
  • Hide word diff
+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(0);
+    $fh->sysseek(0, SEEK_END);
+
+    my $reactor = $self->ioloop->reactor;
+    $reactor->io($fh =>
+        sub {
+            my ($ret, $buf);
+
+            while ($ret = $fh->read($buf, 1024)) {
+                if (0 == $ret) {
+                    $fh->seek(0, SEEK_CUR); # clear eof
+                    last;
+                } elsif (!defined $ret) {
+                    $fh->seek(0, SEEK_CUR); # clear 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;
HTTPS SSH

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