Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I get extra CR using TT (perl template toolkit)

I use perl v5.10 (on windows 7) + TT v2.22. When I use TT, for each source line, I get in the produced html an extra CR :

Source text (windows format):

"Some_html" CR LF  

Output text :

"Some_html" CR  
CR LF

However, when I convert my source file to unix format, and then I run TT, I get :
Source text (unix format):

"Some_html" LF   

Output text :

"Some_html" CR LF

(I use notepad++ to show the CR & LF characters; also to change unix <-> windows formats in the source template).

When I google the problem, I get some (few) posts about extra ^M on windows, but I couldn't find explanation as for the root cause neither a true solution (just some workaround how to get rid of extra ^M).

Although not a real problem, I find it quite "unclean".
Is there some configuration that i should turn on (I reviewed www.template-toolkit.org/docs/manual/Config.html but could not find anything) ?
Some other solution ? (other than post-fixing the output file).
Thanks

like image 271
gerard Avatar asked Feb 03 '12 03:02

gerard


1 Answers

Template Toolkit reads source files for templates in binary mode, but writing in text mode. Data from template (that contains CR LF) are translated during output in text mode, so the LF becomes CR LF.

The easiest solution for the problem is to write files in binary mode (note the raw modifier to open call):

my $tt = Template->new;
my $output_file = 'some_file.txt';
open my $out_fh, '>:raw', $output_file    or die "$output_file: $!\n";
$tt->process('template', \%data, $out_fh) or die $tt->error();
like image 50
bvr Avatar answered Sep 24 '22 10:09

bvr