If the last byte of the binary data is 0x0D, the logged data will miss a 0x0D character.

\x0D should not disappear. I suspect you're in Windows, and that you didn't binmode the filehandle from which you are reading. Be sure to use binmode on both the handle from which you are reading and the one to which you are writing.

sysread returned immediately whenever new data arrived serial port,

That read and sysread are not guaranteed to return LENGTH bytes is documented. If you need more bytes, just use a loop.

my $buf = ''; my $offset = 0; DATA: for (;;) { # For each record my $buf = ''; my $offset = 0; my $rec; do { # Until we have a record. my $len = sysread(STDIN, $buf, 1024, $offset); die("Unable to read from XXX: $!\n") if not defined $len; die("Unable to read from XXX: Premature end of file\n") if not $len and $offset; last DATA if not $len; my $pos = index($buf, "\x0D\x0A", $offset); $offset += $len; } while $pos < 0; $rec = substr($buf, 0, $pos+2); $buf = substr($buf, $pos+2); ... process $rec ... }

Update: Optimized the code slightly.


In reply to Re: Problem with logging binary data through serial port by ikegami
in thread Problem with logging binary data through serial port by jerryleo

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.