Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re^3: Problems parsing UTF16 file

by graff (Chancellor)
on Aug 11, 2012 at 18:19 UTC ( #986915=note: print w/replies, xml ) Need Help??

in reply to Re^2: Problems parsing UTF16 file
in thread Problems parsing UTF16 file

I should mention that if you open the input file like this:
open( $fh, "<:encoding(UTF-16)", $filename );
(that is, without the "LE" in the encoding spec), then you won't need this line:
because the "unmarked" version of UTF-16 encoding requires that a stream-initial BOM be provided on input, and the initial BOM is stripped from input as a result.

For output of UTF-16, if you're trying to match a particular byte order, it'll be best for the code to state this explicitly, because the "default" output order might be different, depending on your machine and environment.

Of course, whenever a file is written with 'UTF-16' encoding, the initial BOM is always included, which should make it possible for any other process to read the file correctly - but of course, not all processes that expect UTF-16LE (or BE) will live up to that specification.

Anyway, when you do decide to be explicit about byte order for an output file, then you should also be sure to include the initial BOM (because it won't be supplied by default). So if you try out the snippet below, see whether there's any difference in the output when you comment out the "UTF-16" open statement and uncomment the two lines that use "UTF-16LE" instead:

open( I, "<:encoding(UTF-16)", $ARGV[0] ) or die "$ARGV[0]: $!"; local $/; $_=<I>; @lines = split /\r\n/; # open(O,">:encoding(UTF-16LE):crlf","$ARGV[0].new") or die "$ARGV[0]. +new:$!"; # print O "\x{feff}"; open(O,">:encoding(UTF-16):crlf","$ARGV[0].new") or die "$ARGV[0].new: +$!"; print O "$_\n" for ( @lines );

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://986915]
[1nickt]: I am stumped, maybe someone brainy can clear my mind?
[1nickt]: This code does what I expect on the CLI: perl -wE 'sub x { 0 and 1 } say x()'
[1nickt]: (prints "0")
[Corion]: Hi 1nickt!
[1nickt]: When I put it in a file, I get the following: "Replacement list is longer than search list at line 4. syntax error at line 4, at EOF ...
[1nickt]: ... (Might be a runaway multi-line ;; string starting on line 3)"
[erix]: ( ha, the inmates of the retirement home have taken the kids to the cafe -- Good! :) )
[1nickt]: (there are three lines in the file)
[erix]: na namesti ( "At The German" ? )
[1nickt]: great goddess almighty, it's the subroutine name!

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2017-12-12 13:36 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (332 votes). Check out past polls.