is there any way to automagically determine what encoding a file is?

That's precisely what the BOM ("byte order mark") is for. If, when creating files, you don't specify a byte order, Perl will create a BOM for you (otherwise, the file will be "BOM-less"). Files created that way (without explicit byte order) can be read by using plain :encoding(utf16):

$ /usr/bin/perl use strict; use warnings; my $c = 'a'; my $fd; open $fd, '>:encoding(utf16le)', 'foo-le' or die "open: $!"; print $fd $c; close $fd; open $fd, '>:encoding(utf16be)', 'foo-be' or die "open: $!"; print $fd $c; close $fd; open $fd, '>:encoding(utf16)', 'foo' or die "open: $!"; print $fd $c; close $fd; __END__ $ xxd foo-le 0000000: 6100 a. $ xxd foo-be 0000000: 0061 .a $ xxd foo 0000000: feff 0061 ...a $ /usr/bin/perl open my $fd, '<:encoding(utf16)', 'foo' or die "open: $!"; print while <$fd>; close $fd; __END__ a

Update: Of course, I realized after clicking in "Create" that I really didn't answer your actual question :^). Well, if files don't have a BOM, you can only guess or brute-force them. Or add a BOM to them ;^).

.

--
David Serrano


In reply to Re^5: Unicode and text files by Hue-Bond
in thread Unicode and text files by dirtdart

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.