我有一个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}}; }