The following reads $block_size at a time (efficient), and keeps at most $max_line_size in memory at a time.

my $block_size = 1000; my $max_line_size = 10000; my $buf = ''; my $offset = 0; my $read; my $line; my $pos; READ_LINE: for (;;) { EXTRACT_LINE: for (;;) { $pos = index($buf, $/); if ($pos >= 0) { $line = substr($buf, 0, $pos+1, ''); $offset = 0; last EXTRACT_LINE; } FILL_BUF: for (;;) { my $to_read; if ($offset + $block_size > $max_line_size) { $to_read = $max_line_size - $offset; } else { $to_read = $block_size; } if (not $to_read) { SKIP_LONG_LINE: for (;;) { $read = read($fh, $buf='', $block_size, $offset=0); die("Unable to read: $!") if not defined $read; if (not $read) { $line = undef; $offset = 0; last READ_LINE; } $pos = index($buf, $/); if ($pos >= 0) { substr($buf, 0, $pos+1, ''); $offset = $read - ($pos+1); last SKIP_LONG_LINE; } } next EXTRACT_LINE; } $read = read($fh, $buf, $to_read, $offset); die("Unable to read: $!") if not defined $read; if (not $read) { if (not $offset) { $line = undef; $offset = 0; last READ_LINE; } else { $line = $buf; $buf = ''; $offset = 0; last EXTRACT_LINE; } } $pos = index($buf, $/, $offset); if ($pos >= 0) { $line = substr($buf, 0, $pos+1, ''); $offset = 0; last EXTRACT_LINE; } $offset += $read; } } ...do something with $line... }

Untested.


In reply to Re: Reading files, skipping very long lines... by ikegami
in thread Reading files, skipping very long lines... by Excalibor

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.