http://qs321.pair.com?node_id=670229


in reply to Re: Temporary text files with File::Temp
in thread Temporary text files with File::Temp

I think it's a laudable goal to write code that's 100% portable, and works properly on all platforms without any special casing. Realistically, I don't think that's possible for any perl program of any significant complexity.

To a large extent, I agree. It can be very difficult to write Perl programs of significant complexity that are 100% portable, especially if you're not practiced in doing such.

However, I'm not talking about writing Perl programs of any complexity in this question. I don't think it should be hard to open a temporary text file and be able to print stuff including newlines to it, and have the right thing happen. Regardless of operating system. This is an introductory course to Perl after all.

My students should be able to write:

# Reverses each line in the given file # and replaces that file with the reversed copy use File::Temp qw(tempfile); use File::Copy qw(move); use Fatal qw(open close move); my $filename = shift or die "Usage: $0 filename"; open(my $in, "<", $filename); my ($tmp_fh, $tmp_name) = tempfile(); while(<$in>) { chomp; print {$tmp_fh} scalar(reverse($_)), "\n"; } close $in; close $tmp_fh; move($tmp_name, $filename);

and expect it to work flawlessly on any operating system that has Perl installed. There's nothing in that code which would suggest to a Perl novice (or me until last week) that that code isn't portable.

I realise that it's fundamentally a question of what the logical default case should be. File::Temp has several choices; always binmode the file, never binmode the file, binmode the file if passed a flag, don't binmode the file when passed a flag. They've chosen the first, I was hoping there might have been an undocumented way to get the last.

Alternately if there is a special layer I can pass to binmode itself to say "treat as text" so that Perl can do it's special text-file magic by translating \n to the appropriate thing; I'd love to hear about that. This isn't achieved by using the :crlf layer, because that layer is Windows specific, and won't do the right thing under the *nixes.

Any other suggestions?

thanks, jarich