是否有任何方式可以用标准perl库打开文件并进行编辑,而不必关闭它然后再打开它?我所知道的只是将文件读入字符串中,然后用新文件覆盖文件;或者读取并附加到文件的末尾。在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 + views and only 1 upvote。 。 。 – GlassGhost 2013-01-04 21:28:38
2 upvotes now:D – GLES 2013-01-26 23:14:50