Depending on what you want to do with your 'raw' filehandle, then using:

open(my $fh, '<', $filename); binmode($fh);
...may not be appropriate (at least on windows).

If you want to read raw bytes from a filehandle (for example to look for a BOM) and _then_ add an encoding layer then you need to ensure that there isn't a :crlf layer hanging around to begin with which the above has (it may not be enabled, but it's still there *). This is because of :crlf not working nicely with encodings eg. it breaks tell().

So, the method i use is:

open(my $fh, "<:raw:perlio", $file); # read first few bytes for a BOM or ASCII in utf(16|32) # to determine encoding binmode $fh, ":encoding($encoding)"
* Consider:
open $fh, "<", $^X or die; binmode $fh; print "1: ", join(' ', PerlIO::get_layers($fh, details => 1)), "\n"; close $fh; open $fh, "<:raw:perlio", $^X or die; print "2: ", join(' ', PerlIO::get_layers($fh, details => 1)), "\n"; close $fh;
gives:

1: unix 4195328 crlf 4195328 2: unix 4195328 perlio 4195328

In reply to Re^2: Using ":raw" layer in open() vs. calling binmode() by Anonymous Monk
in thread Using ":raw" layer in open() vs. calling binmode() 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.