package ChunkReader; sub new { my $class = shift; my %args = @_; $args{threshold} = 2048 unless defined $args{threshold}; return bless {%args}, $class; } sub chunk { my $self = shift; unless ( $self->{handle} ) { my $file = shift || $self->{file}; print "Filename is $file\n"; my $handle; open($handle, "<", $file) or die "cannot open '$self->{file}\n'"; $self->{handle} = $handle; } my $handle = $self->{handle} || die "File not open!\n"; my $chunk = $self->{lastline}; # reset last line $self->{lastline} = ''; while ( $line = <$handle> ) { if ( ( length( $chunk ) + length( $line ) ) > $self->{threshold} ) { # unless we already read a chunk # (when a single line is bigger than the threshold) unless ( $chunk ) { #return the line return $line; } else { # save the last line for further use # and return the chunk $self->{lastline} = $line; return $chunk; } } else { # append line and keep going $chunk .= $line; } } #end of file return $chunk; } 1;