in reply to Read a line up to a maximum length
... but with error handling, of course. Need I mention that you shouldn't mix this fgets() with any other filehandle operations?{ my %buffers, %handles; sub fgets { my $fh = shift; my $max = shift; my $needed = $max - length $buffers{$fh}; $buffers{$fh} .= do {local $/ = \$needed; <$fh>} if $needed > 0; open $handles{$fh}, '<', \$buffers{$fh} unless $handles{$fh}; my $result = substr(readline $handles{$fh}, 0, $max); substr($buffers{$fh}, 0, length $result) = ''; seek $handles{$fh}, 0, 0; return $result; } } # test code open my $fh, '<', $0; while(my $line = fgets $fh, 20) { print "[$line]"; }
|
|---|