在perl中打开文件进行读写(而不是追加)

在perl中打开文件进行读写(而不是追加),perl,file,file-io,Perl,File,File Io,标准perl库有没有办法打开并编辑一个文件,而不必先关闭它,然后再打开它?我所知道的只是将文件读入字符串,关闭文件,然后用新文件覆盖文件;或者读取,然后附加到文件的末尾 以下各项目前有效,但:;我必须打开和关闭两次,而不是一次: #!/usr/bin/perl use warnings; use strict; use utf8; binmode(STDIN, ":utf8"); binmode(STDOUT, ":utf8"); use IO::File; use Cwd; my $owd =

标准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
    }
}
#/usr/bin/perl
使用警告;严格使用;
使用utf8;binmode(标准输入“:utf8”);binmode(标准输出,“:utf8”);
使用IO::文件;使用化学武器;我的$owd=getcwd()。“/”;#原始工作目录
使用Text::Tabs qw(展开未展开);
$Text::Tabs::tabstop=4#设置选项卡中的空格数
opendir(DIR,$owd)| | die“$!”;
my@files=grep{/(.*)\(c|cpp|h|java)/}readdir;
foreach my$x(@files){
我的$str;
my$fh=新IO::文件(“+”$owd.$x);
如果(定义为$fh){
打印$fh$str;#这只是附加到文件中
undef$str;undef$fh;#自动关闭文件
}
}

您已经以
1k+视图模式打开了该文件,并且只打开了一个upvote@霍布斯,这个过程是以生产线为基础的。如果我想使用包含换行符的regexp怎么办?@solotim取决于细节。您可以将
$/
更改为比
“\n”
更合适的内容-特别是,如果将
$/
设置为
undef
,则perl将在一次读取中读取整个文件内容,让您修改它们,然后再写回。内存足够大,对于许多文件来说,这是一种合理的方法。但如果不是,你需要自己做这项工作。
#!perl
use strict;
use warnings;
use Text::Tabs qw(expand unexpand);
$Text::Tabs::tabstop = 4;

my @files = glob("*.c *.h *.cpp *.java");

{
   local $^I = ""; # Enable in-place editing.
   local @ARGV = @files; # Set files to operate on.
   while (<>) {
      s/( |\t)+$//g; # Remove trailing tabs and spaces
      $_ = expand($_); # Expand tabs
      s{//(.*)$}{/*$1*/}g; # Turn //comments into /*comments*/
      print;
    }
}