標準のperlライブラリでファイルを開いて編集する方法はありますか?私が知る限り、ファイルを文字列に読み込んでファイルを閉じ、ファイルを新しいファイルで上書きするか、ファイルを読み込んだ後にファイルの末尾に追加します。perlで読み書き用のファイルを開く(追加しない)
以下は現在動作していますが、私が代わりに一度、それを開いて、それを2回クローズする必要があります。
#!/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と1 upvoteのみです。 。 。 – GlassGhost
2 upvotes now: '$^I'のためにD – GLES