views:

393

answers:

2

I have this warning every time I run my CGI-script (output is rendered by Template::Toolkit):

Wide character in print at /usr/local/lib/perl5/site_perl/5.8.9/mach/Template.pm line 163.

What's the right way to eliminate it?

I create the tt object using this config:

my %config = (
       ENCODING     => 'utf8',
       INCLUDE_PATH => $ENV{TEMPLATES_DIR},
       EVAL_PERL   => 1,
}
my $tt = Template->new(\%config); 
+1  A: 

Put this before calling $tt->process() to have the output automatically encoded:

binmode STDOUT, ":encoding(utf8)";

Edit: As daxim mentioned, it's possible to utilize TT's encoding facilities:

$tt->process($infile, $vars, $outfile, { binmode => ':encoding(UTF-8)' })

The manpage states that this option sets the output file to binary mode. But if we supply '-' (dash) as a filename, STDOUT will be used instead. This happens because the '-' filename is special, and gives you STDIN when it's opened for reading, and STDOUT when it's opened for writing. This is a widely used convention.

eugene y
http://ahinea.com/en/tech/perl-unicode-struggle.html
David Dorward
Does this auto-encode the output into any encoding? If so, its great!
planetp
@planetp: Yes. See http://perldoc.perl.org/perlunifaq.html#Is-there-a-way-to-automatically-decode-or-encode?
eugene y
Downvote because TT has perfectly fine encoding facilities on its own. See my answer that does not require changing global state.
daxim
A: 
$tt->process($infile, $vars, $outfile, { binmode => ':encoding(UTF-8)' })

This is documented in http://search.cpan.org/perldoc?Template#process%28%24template%2C_%5C%25vars%2C_%24output%2C_%25options%29.

daxim
This seems to work only when outputing to file: `The only option currently supported is binmode which, when set to any true value will ensure that files created (but not any existing file handles passed) will be set to binary mode.`
eugene y
Your speculation is false. Care to undo your vote? Why didn't you just test it yourself first instead of blabbing around? `Template->new->process(\'foo [% bar %] quux', {bar => "\x{4e71}"}, '-', { binmode => ':encoding(GB2312)' });`
daxim
@daxim: I'd like your answer better if it included this example and explained what the special `"-"` filename mean by convention.
eugene y