Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • I'm not sure I understand the concern as long as the temporary files are actually temporary -- meaning that they aren't going to persist past the program or be transferred to another machine. So what if the newlines are LF instead of CRLF? As long as Perl treats it all as "\n" when reading and writing, isn't that good enough?

    -- dagolden
    • One of my common uses of temporary files is to allow me to make changes to a whole file, know that that all succeeded and then replace said file. For example, to reverse each line in a file I might write:

      # Reverses each line in a file
      use File::Temp qw(tempfile);
      use File::Copy qw(move);
      use Fatal qw(open close move);

      # Open files
      my $filename = shift or die "Usage: $0 filename";
      open(my $in, "<", $filename);
      my ($tmp_fh, $tmp_name) = tempfile();

      # Read line in, remove newline, reverse and print it
      while(<$in>) {
              chomp;
              print {$tmp_fh} scalar(reverse($_)), "\n";
      }

      # Close files.  If no errors here, then everything succeeded!
      close $in;
      close $tmp_fh;

      # Move temp-file over original
      move($tmp_name, $filename);

      This is a case of using a temporary file - temporarily - but wanting to keep the result permanently. Sure it's a contrived example (one of the exercises from our class in fact), but it should show why not treating \n correctly becomes a problem in the end result.