質問

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?

役に立ちましたか?

解決

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

他のヒント

I use File::Temp for this.

But you should have in mind that File::Temp deletes the file by default. That is OK but in my case I don't want that when debugging. If the script terminates and the output is not the desired one I can not check the temp file.

So I prefer to set $KEEP_ALL=1 or $fh->unlink_on_destroy( 0 ); when OO or ($fh, $filename) = tempfile($template, UNLINK => 0); and then unlink the file myself or move to a proper place.

It would be safer to move the file after closing the filehandle (just in case there is some buffering going on). So I would prefer an approach where temp file is not deleted by default and then when all is done, set a conditional that either delete it or move it to your desired place and name.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top