Search code examples
perlfile-handlingtemporary-files

perl: open filehandle, write into it, give it a name later on?


I think I've read how to do this somewhere but I can't find where. Maybe it's only possible in new(ish) versions of Perl. I am using 5.14.2:

I have a Perl script that writes down results into a file if certain criteria are met. It's more logical given the structure of the script to write down the results and later on check if the criteria to save the results into a file are met.

I think I've read somewhere that I can write content into a filehandle, which in Linux I guess will correspond to a temporary file or a pipe of some sorts, and then give the name to that file, including the directory where it should be, later on. If not, the content will be discarded when the script finishes.

Other than faffing around temporary files and deleting them manually, is there a straightforward way of doing this in Perl?


Solution

  • There's no simple (UNIX) facility for what you describe, but the behavior can be composed out of basic system operations. Perl's File::Temp already does most of what you want:

    use File:Temp;
    
    my $tmp = File::Temp->new;      # Will be unlinked at end of program.
    
    while ($work_to_do) {
      print $tmp a_lot_of_stuff();  # $tmp is a filehandle
    }
    
    if ($save_it) {
      rename($tmp, $new_file);      # $tmp is also a string.  Move (rename) the file.
    }                               # If you need this to work across filesystems, you
                                    # might want to ``use File::Copy qw(move)'' instead.
    
    exit;                           # $tmp will be unlinked here if it was not renamed