It is very common practice to use variations of a pattern like this in Perl programs:
while (<$fh>) { # do something with one line of input }

However, if I can't trust my input --and who can?-- this is unsafe, as the program might come upon a line that is too long to fit into memory. Perl will happily keep allocating space to store it until the process runs out of virtual memory, which may happen only after the system has suffered serious performance loss trying to satisfy the demand.

In order to survive malformed input while keeping the normal procedure line-oriented, I need perhaps a getline variant with some sort of length limitation. I'd like to be able to give up gracefully when excessively long lines are detected.

Do you, fellow monks, know of a good way to handle this?

I know about sysread and could with some effort write a wrapper around it to reassemble fixed-length chunks into lines, but am quite open to learn about alternatives first.

Update: This topic has indeed been discussed here before: Read a line with max length ?. Thanks to runrig for a pointer to File::GetLineMaxLength. I'll follow up with a report once I have looked into it.


In reply to Safely reading line by line by martin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.