IO::InSitu

IO::InSitu is a Perl module to avoid clobbering files opened for both input and output.
Download

IO::InSitu Ranking & Summary

Advertisement

  • Rating:
  • License:
  • Perl Artistic License
  • Price:
  • FREE
  • Publisher Name:
  • Damian Conway
  • Publisher web site:
  • http://search.cpan.org/~dconway/

IO::InSitu Tags


IO::InSitu Description

IO::InSitu is a Perl module to avoid clobbering files opened for both input and output. IO::InSitu is a Perl module to avoid clobbering files opened for both input and output.SYNOPSIS use IO::InSitu; my ($in, $out) = open_rw($infile_name, $outfile_name); for my $line () { $line =~ s/foo/bar/g; print {$out} $line; }When users want to do in-situ processing on a file, they often specify it as both the input and output file: > myapp -i sample_data -o sample_data -op=normalizeBut, if the -i and -o flags are processed independently, the program will usually open the file for input, open it again for output (at which point the file will be truncated to zero length), and then attempt to read in the first line of the now-empty file: # Open both filehandles... use Fatal qw( open ); open my $src, '', $destination_file; # Read, process, and output data, line-by-line... while (my $line = < $src >) { print {$dest} transform($line); }Not only does this not perform the requested transformation on the file, it also destroys the original data. Fortunately, this problem is extremely easy to avoid: just make sure that you unlink the output file before you open it: # Open both filehandles... use Fatal qw( open ); open my $src, '', $destination_file; # Read, process, and output data, line-by-line... while (my $line = ) { print {$dest} transform($line); }If the input and output files are different, unlinking the output file merely removes a file that was about to be rewritten anyway. Then the second open simply recreates the output file, ready for writing.If the two filenames actually refer to a single in-situ file, unlinking the output filename removes that filename from its directory, but doesn't remove the file itself from the filesystem. The file is already open through the filehandle in $input, so the filesystem will preserve the unlinked file until that input filehandle is closed. The second open then creates a new version of the in-situ file, ready for writing.The only limitation of this technique is that it changes the inode of any in-situ file . That can be a problem if the file has any hard-linked aliases, or if other applications are identifying the file by its inode number. If either of those situations is possible, you can preserve the in-situ file's inode by using the open_rw() subroutine that is exported from this module: # Open both filehandles... use IO::InSitu; my ($src, $dest) = open_rw($source_file, $destination_file); # Read, process, and output data, line-by-line... while (my $line = ) { print {$dest} transform($line); } Requirements: · Perl


IO::InSitu Related Software