【发布时间】:2018-05-15 20:24:05
【问题描述】:
我是 Perl 的新手,已经使用它大约一天了。我正在尝试编写一个脚本,该脚本将转到每个 .cpp 文件和 .hpp 文件更改文件的读写权限,同时还搜索字符串并替换它。这就是我到目前为止所拥有的。我能够更改每个文件的读写权限问题是当我尝试替换字符串时。它打印正确,但不会保存到文件中。欢迎提出任何建议。
#gets first first value of array being past as argument.
my $path = shift;
#open directory
opendir(DIR, $path) or die "Unable to open $path: $!";
#read in the files
#ignores hidden files eg. .\..\
my @files = grep{!/^\.{1,2}$/} readdir(DIR);
#close directory
close(DIR);
#put full path of file
@files = map {$path . '\\' . $_ } @files;
for (@files){
#if directory then use recusrion to open file
if(-d $_){
change_permission($_);
}elsif((-f $_) && (($_ =~m/\.cpp/) || ($_ =~m/\.hpp/) || ($_ =~m/\.txt/))){
chmod 0666, $_ or die "Couldn't chmod";
open(DATA, "+<", $_) or die "file could not open $! \n";
while(<DATA>){
s/best/worst/ig;
print;
}
close(DATA) or die "Couldn't close file properly $! \n" ;
}
}
【问题讨论】:
-
欢迎使用 Stack Overflow 和 Perl 标签。如果除了您的问题的答案之外,您还想获得一些关于您的代码的建设性反馈,请随时将其发布到 perl 标记和 beginnerCode Review /i> 那里。我在这里看到了一些可以改进的地方。
-
相关,可能是重复的,但需要对程序进行重大更改:stackoverflow.com/q/31024980/1331451
-
简而言之,您的
print打印到STDOUT;就像print STDOUT $_;。它不能也不应该神奇地更改文件。您应该将新内容写入另一个文件,然后将其移到原始文件上。例如,查看in perlfaq5,然后搜索 SO 帖子。 -
我建议不要使用
'+<'模式。读取'<'或写入'>'或附加'>>'。