<?xml version="1.0" encoding="windows-1252"?>
<node id="670208" title="Temporary text files with File::Temp" created="2008-02-25 22:25:18" updated="2008-02-25 17:25:18">
<type id="115">
perlquestion</type>
<author id="125487">
jarich</author>
<data>
<field name="doctext">
&lt;p&gt;
I teach Perl to programmers using both *nix and Windows operating systems.  One of the suggestions I give them is to use &lt;code&gt;File::Temp&lt;/code&gt; for temporary files.  It's a great module, especially because it's standard so everyone will already have it.
&lt;/p&gt;
&lt;p&gt;
Unfortunately, I've just discovered that File::Temp doesn't exactly do what I want it to.  When my students using *nix open temporary text files, everything just works.  When my students using Windows open temporary text files, their newlines (\n) are not correctly translated into crlf.  
&lt;/p&gt;
&lt;p&gt;
[John M. Dlugosz] touched on the problem a couple of years ago in [Why does File::Temp use sysopen?] but he was blaming the wrong cause.  File::Temp uses binmode (or an equivalent) if it can.  It says so in the [cpan://File::Temp|documentation].
&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;b&gt;BINMODE&lt;/b&gt;&lt;/p&gt;
&lt;p&gt;
The file returned by File::Temp will have been opened in binary mode if such a mode is available.    If that is not correct, use the binmode() function to change the mode of the filehandle.
&lt;/p&gt;
&lt;p&gt;
Note that you can modify the encoding of a file opened by File::Temp also by using binmode().
&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;
The [perldoc://binmode|binmode documentation] says:
&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;
For the sake of portability it is a good idea to always
use it when appropriate, and to never use it when it isn't
appropriate.
&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;
I realise I can "fix" File::Temp's use of binmode for text files by calling binmode:
&lt;/p&gt;
&lt;code&gt;
my ($tmp_fh, $tmp_name) = tempfile();
binmode($tmp_fh, ":crlf" );
&lt;/code&gt;
&lt;p&gt;
but I don't want to teach that.  I want an easy, 100% portable way of doing it.  I want my students to be able to write exactly the same code on either system and have it work - even for text files.
&lt;/p&gt;
&lt;p&gt;
Am I missing an easier way of doing this?
&lt;/p&gt;</field>
</data>
</node>
