Created
April 28, 2014 10:02
-
-
Save fgabolde/11367436 to your computer and use it in GitHub Desktop.
Use IO::Scalar to read data chunks line by line
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use 5.010; | |
use Carp; | |
use autodie; | |
use utf8; | |
use IO::Scalar; | |
my @chunks = ( | |
qq{I'm a chunk! but I'm not a complete line}, | |
qq{ ... the second chunk completes this line\nand adds another line\nand starts a third}, | |
qq{ ... this is my EOF}); | |
my $buffer = ''; | |
my $sh = IO::Scalar->new(\$buffer); | |
while (my $chunk = shift @chunks) { | |
$buffer .= $chunk; | |
while (my $line = $sh->getline) { | |
# remove what we just read from the buffer | |
substr($buffer, 0, length($line), ''); | |
$sh->seek(0, 0); | |
unless (chomp $line) { | |
say "partial line: $line"; | |
$buffer = $line . $buffer; | |
last; # and wait for the next chunk | |
} | |
say "got a complete line: $line"; | |
} | |
} | |
say "this is the remainder: " . $sh->getline; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment