http://www.perlmonks.org?node_id=670208

jarich has asked for the wisdom of the Perl Monks concerning the following question:

I teach Perl to programmers using both *nix and Windows operating systems. One of the suggestions I give them is to use File::Temp for temporary files. It's a great module, especially because it's standard so everyone will already have it.

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.

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 documentation.

BINMODE

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.

Note that you can modify the encoding of a file opened by File::Temp also by using binmode().

The binmode documentation says:

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.

I realise I can "fix" File::Temp's use of binmode for text files by calling binmode:

my ($tmp_fh, $tmp_name) = tempfile(); binmode($tmp_fh, ":crlf" );

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.

Am I missing an easier way of doing this?