in reply to utf8 encoding and warnings woe

You just need to do binmode OUTVAR2, ":utf8"; before you print any wide characters to that output file handle.

UTF-8 output mode is not turned on by default, nor is it automatically set when scalars whose utf8 flag is set happen to be printed to the file handle.

(update: you should do binmode STDOUT, ":utf8"; as well, if you're going to print wide characters to STDOUT.)

Another update: (sorry -- I should have read the whole post, carefully, sooner) So you are printing utf8 data to an in-memory scalar-variable-as-file, and then you want to just print the contents of that scalar as if it were not an in-memory file (but just a utf8 string).

The problem there is that using the scalar as a file makes it impossible for perl to realize that it's really a utf8 string (the fact that you "opened" the file with ">:utf8" does not cause the variable's "utf8 flag" to be turned on).

So if you want perl to treat that variable as a utf8 string, you have to set the utf8 flag, and the supported way to do that is to use Encode::decode...

use Encode; # ... treat $output2 as an output file, then: $output2 = decode( "utf8", $output2 ); # assuming that STDOUT is set to utf8 mode, you can now safely print "$output2\n";
When the utf8 flag isn't set, but there are high-bit bytes in the string and the output file handle is set to utf8, perl will pretend that the string is actually Latin1, and "promote" it to utf8, which of course is a form of corruption in your case.

Replies are listed 'Best First'.
Re^2: utf8 encoding and warnings woe
by GrandFather (Saint) on Oct 31, 2006 at 02:18 UTC

    Ah, that makes a heap of sense - thank you.

    Actually putting the binmode STDOUT, ":utf8"; after the 'corrupting' print:

    print "\n" . $output2; binmode STDOUT, ":utf8"; print "\n$str";

    'fixes' the problem too, but isn't near as clean as the decode solution.


    DWIM is Perl's answer to Gödel
Re^2: utf8 encoding and warnings woe
by GrandFather (Saint) on Oct 31, 2006 at 01:53 UTC

    I don't need binmode OUTVAR2, 'utf8'; because I already opened the handle in utf8 mode (OP: "Changing the open to use '>:utf8'...").

    If I add binmode STDOUT, ":utf8"; then I get the OUTVAR2 streamed text double encoded (as indicated in the OP).


    DWIM is Perl's answer to Gödel