How to delay creating a text file until I actually write a line to it? (lazy creation)

I have a perl script that adds text to a file:

open (EXFILE, ">>$outFile"); 

an empty file is created at the time of opening, I want to avoid this. I want the file to be created only the first time the line is written to the file descriptor:

 print EXFILE $line 

If nothing is written to the file descriptor, the file should not be created ...

Is it possible? How?

+4
source share
3 answers

Create a subsection that makes a discovery for you.

 sub myappend { my ($fname, @args) = @_; open my $fh, '>>', $fname or die $!; print $fh @args; close $fh or die $!; } myappend($outfile, $line); 

Alternatively, instead of printing, click on the array and wait for the print to finish. A.

 while ( ... ) { push @print, $line; } if (@print) { open my $fh, '>>', $outfile or die $!; print $fh @print; } 

Or, for multiple files

 while ( ... ) { push @{$print{$outfile}}, $line; } for my $key (%print) { open my $fh, '>>', $key or die $!; print $fh @{$print{$key}}; } 
+6
source

I thought it would be the easiest object to print in the file when it is about to be destroyed.

 package My::Append; use strict; use warnings; sub new { my($class,$filename) = @_; my $self = bless { filename => $filename, }, $class; return $self; } sub append{ my $self = shift; push @{ $self->{elem} }, @_; return scalar @_; } sub append_line{ my $self = shift; push @{ $self->{elem} }, map { "$_\n" } @_; return scalar @_; } sub filename{ my($self) = @_; return $self->{filename}; } sub DESTROY{ my($self) = @_; open my $fh, '>>', $self->filename or die $!; print {$fh} $_ for @{ $self->{elem} }; close $fh or die $!; } 

Used as follows:

 { my $app = My::Append->new('test.out'); $app->append_line(qw'one two three'); } # writes to file here 
+1
source

How about something like this:

 #!/usr/bin/env perl use strict; use warnings; my $fh; sub myprint { unless ($fh) { open $fh, '>', 'filename'; } print $fh @_; } myprint "Stuff"; # opens handle and prints myprint "More stuff"; # prints 

NB not verified but should work

+1
source

Source: https://habr.com/ru/post/1386498/


All Articles