![]() |
|
"be consistent" | |
PerlMonks |
Re: Read a line with max length ?by graff (Chancellor) |
on Feb 27, 2003 at 04:02 UTC ( #238998=note: print w/replies, xml ) | Need Help?? |
There is a detail in "perldoc perlvar" about assigning an integer value to $/, which led me to discover the following, which I think is just what you want:
I haven't tested this thoroughly in terms of what happens with underlying input buffers, but in terms of the behavior of variables and values within the perl script, it seems to do exactly what you'd like. Setting $/ to \1 means the input record size is one byte; the while loop will append one
No doubt this will raise some hackles because it seems like a really non-optimal amount of overhead for reading input; maybe you can set $/ to $maxlen, but then if you're really expecting to do line-oriented input, and you're going back for additional reads during a given connection, you have to worry about making sure that any residue that follows a line termination is carried over to the next time that you clear $line to start filling it again. One way or another, you pay extra for being really careful (so just believe that it ends up less expensive than being left open to hackers).
UPDATE: Having thought about this a bit more, I think that any approach that tries to read more than one byte at a time will get into a lot of trouble, if your intention is really to do line-oriented input safely. The point is that, as soon as you leave behind the default value of $/ and expect some minimum number of bytes greater than one on each read, you run the risk that (a closing portion of) a line will be left stranded in the input buffer until either: (a) more stuff is written by the remote host to fill the buffer, or (b) you close the connection. This would hose your process, putting it into an indefinite wait. I bow to Elian's more informed experience on this issue -- but also second Zaxo's point about making sure to watch for multiple lines in one read. Thanks, folks!
In Section
Seekers of Perl Wisdom
|
|