我需要一些快速的perl帮助。 以下是我想做的。
1)从命令行运行我的perl脚本,并传入一个数据文件作为参数2)搜索传入的数据文件,并寻找字符串中第一次出现的单词。3)将更新后的文件保存到自己的文件中(在文件中替换)。
所以,例如,像这样的东西。
./myPerlScript.pl data.txt
数据文件是这样的:
_DATA__
path/to/some/file
path/to/some/other/file
path/to/SUBTSTRING/file #replace entire line if SUBSTRING is found
path/to/file
但实际的 data.txt
是更新的(不是写入新的文件)。
和其他语言一样。
use Fcntl qw( SEEK_SET );
my $qfn = $ARGV[0];
open(my $fh, '+<', $qfn)
or die("Can't open \"$qfn\": $!\n");
# Read contents of file into $file.
my $file; { local $/; $file = <$fh>; }
if ($file =~ s/^.*SUBSTR.*/foo/mg) {
seek($fh, 0, SEEK_SET)
or die("seek: $!\n");
truncate($fh, 0)
or die("truncate: $!\n");
print($fh $file)
or die("print: $!\n");
close($fh)
or die("close: $!\n");
}
另一种方法。
这是在使用足够新的Perl版本时,执行以下操作时的情况。
perl -nle'print /SUBSTR/ ? "foo" : $_' -i file
我们可以通过 $^I
$^I = '';
while (<>) {
chomp;
say /SUBSTR/ ? "foo" : $_;
}
这种方法有两个优点。
还有三个缺点。