Use a buffer.

[how do I ensure that I don't messages] off midway in between reads?

When you've found a message, add to the buffer until you find the end of message.

how do I ensure I don't save the same messages twice?

Remove them from the buffer as you process them.

how do I ensure that I don't skip any messages

I don't see how that could happen.

Untested solution:

my $BLOCK_SIZE = 64 * 1024; # Until EOF, for (;;) { # Read a chunk. my $rv = read($fh, my $buf='', $BLOCK_SIZE); die if !defined($rv); # I/O error. last if !$rv; # EOF # For each message in the buffer, for (;;) { my $pos = index($buf, "\0\0Msrc"); last if $pos < 0; # Discard the uninteresting bits. substr($buf, 0, $pos, ''); # Read the header. while (length($buf) < 22) { my $rv = read($fh, $buf, $BLOCK_SIZE, length($buf)); die if !defined($rv); # I/O error. die if !$rv; # Incomplete message } # Discard the header. substr($buf, 0, 22, ''); # Locate the end of the message. my $pos = 0; for (;;) { $pos = index($buf, "\0", $pos); last if $pos >= 0; $pos = length($buf); # Read a chunk. my $rv = read($fh, $buf, $BLOCK_SIZE, length($buf)); die if !defined($rv); # I/O error. die if !$rv; # Incomplete message } # Extract the message. my $msg = substr($buf, 0, $pos, ''); # Process the message. do_something($msg); } }

Others ([1] [2] [3] [4]) have assumed the amount of data between messages is rather short. My solution makes no such assumption.

Update: Added answers to direct questions.
Update: Added note concerning assumptions.


In reply to Re: Parsing 12GB Entourage database in pieces... by ikegami
in thread Parsing 12GB Entourage database in pieces... by Anonymous Monk

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.