【发布时间】:2011-05-27 18:26:27
【问题描述】:
标准 perl 库有什么方法可以打开文件并编辑它,而不必关闭它然后再次打开它?我所知道的就是将文件读入字符串关闭文件,然后用新文件覆盖文件;或读取然后追加到文件的末尾。
以下目前有效,但是;我必须打开它并关闭它两次,而不是一次:
#!/usr/bin/perl
use warnings; use strict;
use utf8; binmode(STDIN, ":utf8"); binmode(STDOUT, ":utf8");
use IO::File; use Cwd; my $owd = getcwd()."/"; # OriginalWorkingDirectory
use Text::Tabs qw(expand unexpand);
$Text::Tabs::tabstop = 4; #sets the number of spaces in a tab
opendir (DIR, $owd) || die "$!";
my @files = grep {/(.*)\.(c|cpp|h|java)/} readdir DIR;
foreach my $x (@files){
my $str;
my $fh = new IO::File("+<".$owd.$x);
if (defined $fh){
while (<$fh>){ $str .= $_; }
$str =~ s/( |\t)+\n/\n/mgos;#removes trailing spaces or tabs
$str = expand($str);#convert tabs to spaces
$str =~ s/\/\/(.*?)\n/\/\*$1\*\/\n/mgos;#make all comments multi-line.
#print $fh $str;#this just appends to the file
close $fh;
}
$fh = new IO::File(" >".$owd.$x);
if (defined $fh){
print $fh $str; #this just appends to the file
undef $str; undef $fh; # automatically closes the file
}
}
【问题讨论】:
-
1k + 观看次数,只有 1 次赞成。 . .