我有一个文件文本追加一个perl脚本:如何延迟创建文本文件直到我实际写入一行为止? (懒创造)
open (EXFILE, ">>$outFile");
在打开一个空文件的时刻被创建,我想避免这种情况。我想,该文件将被创建仅在第一次一条线被写入文件句柄:
print EXFILE $line
如果没有被写入文件句柄不应该被创建的文件...
可能吗 ?怎么样 ?
我有一个文件文本追加一个perl脚本:如何延迟创建文本文件直到我实际写入一行为止? (懒创造)
open (EXFILE, ">>$outFile");
在打开一个空文件的时刻被创建,我想避免这种情况。我想,该文件将被创建仅在第一次一条线被写入文件句柄:
print EXFILE $line
如果没有被写入文件句柄不应该被创建的文件...
可能吗 ?怎么样 ?
创建一个可以为你打开的子。
sub myappend {
my ($fname, @args) = @_;
open my $fh, '>>', $fname or die $!;
print $fh @args;
close $fh or die $!;
}
myappend($outfile, $line);
或者,不是打印,而是推入数组并等待打印结束。
while (...) {
push @print, $line;
}
if (@print) {
open my $fh, '>>', $outfile or die $!;
print $fh @print;
}
或者多个文件
while (...) {
push @{$print{$outfile}}, $line;
}
for my $key (%print) {
open my $fh, '>>', $key or die $!;
print $fh @{$print{$key}};
}
我在想,会是什么,将打印出的文件,当它即将被销毁的最简单的对象。
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 $!;
}
像这样来使用:
{
my $app = My::Append->new('test.out');
$app->append_line(qw'one two three');
} # writes to file here
怎么是这样的:
#!/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
注:未经测试,但应该工作
`if`语句是你的朋友。 – 2011-12-15 11:45:50
我不能在这种情况下使用if语句,我需要一个懒惰的创建模式... – aleroot 2011-12-15 11:52:14