This just a very short FYI for anyone who is interested in why read() would refuse to read the "right" number of bytes from a file. In the following snippet I am slurping an entire file and verifying that I read the expected number of bytes. I was getting the error message "Read 3157 but expected 3158 bytes from 002971DD46D2CB2286256BAC002C26FB.xml" and it didn't immediately occur to me that because of the implicit new-line handling on text files, a single \r character had been removed and my $expected was differing from my $got value.

One application of binmode() later and my code worked. This isn't a revelation, perlfunc already documents this but since I had to think about it for moment today I figured I'd just share and let this be a reminder to anyone else who might get something out of it.

sub readfile { my $fname = shift; my $fdata; open XML, "<", $fname or die "Couldn't open $fname: $!"; binmode XML or die "Couldn't binmode $fname: $!"; my $expected = -s XML; my $got = read XML, $fdata, $expected; $expected == $got or die "Read $got but expected $expected bytes from $fname: $!"; close XML or die "Couldn't close $fname: $!"; return \ $fdata; }

In reply to Remember to binmode text files by diotalevi

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.