You fell prey to the idiosyncrasies of C and DOS, who together make a difference between text files and binary files.

Each file is by default in text mode, which means that every byte aequivalent to \n is translated into the byte sequence 0d 0a by Perl or by the underlying OS.

The solution is to always use binmode() on files that you want to handle as binary files.

So, use the following idiom for files that you want Perl to handle as binary files. It dosen't make any difference on systems that don't distinguish text and binary files :

use strict; # Always use strict local *FILE; # This declares FILE as a local variable. # This is NOT necessary for variables with # UPPERCASE names, as strict # ignores these, see [jcwren]s post # below for an excellent explanation. # But localizing a file variable prevents # us from messing up other variables of # the same name. open FILE, "> $filename" or die "Couldn't create '$filename': $!\n"; binmode FILE; # do your stuff close FILE;

Update : In the code above, there was the following statement, which is not true (I didn't know that) :

local *FILE; # With strict, we need to predeclare *FILE # (not necessary for builtin file handles such + as STDIN)
I've changed my main CODE block to reflect what actually happens and why I think that using local is still a good idea :-). Thanks to jcwren, who pointed this out to me (in the below post).


In reply to Re: Problem with Pack by Corion
in thread Problem with Pack by Carl-Joseph

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.