Regex Perl就地替换
在Perl one liner中,我们可以使用Regex Perl就地替换,regex,perl,Regex,Perl,在Perl one liner中,我们可以使用-i参数进行就地替换。在IDE中编写perl代码时,-i的等价性是什么 考虑以下代码: binmode(STDOUT, ':raw'); open my $fh, '<', $filename; while (<$fh>) { s/^/<rootroot>/ if $.==1; if (/(<link rel[^<>\n]*?)(\/?)(>)/g) { my ($
-i
参数进行就地替换。在IDE中编写perl代码时,-i
的等价性是什么
考虑以下代码:
binmode(STDOUT, ':raw');
open my $fh, '<', $filename;
while (<$fh>) {
s/^/<rootroot>/ if $.==1;
if (/(<link rel[^<>\n]*?)(\/?)(>)/g) {
my ($p1, $p2, $p3) = ($1, $2, $3);
s/$p1$p2$p3/($p2 ? qq|$p1$p2$p3<span class="entry">| : qq|$p1\/$p3<span class="entry">|)/ge;
};
s/<\/>/<entry_end><\/entry_end>/;
s/$/<\/rootroot>/ if eof;
}
binmode(标准输出“:raw”);
打开我的$fh,“您可以尝试以下内容:
my $filename = 'test.dat';
@ARGV = ($filename);
$^I = '';
while(<<>>) {
binmode(ARGV, ':raw');
# Do the substitiution on $_ here ...
print;
}
相当于以下类似Perl的伪代码:
unshift(@ARGV, '-') unless @ARGV;
while ($ARGV = shift) {
open(ARGV, $ARGV);
while (<ARGV>) {
... # code for each line
}
}
local$^I=''代码>谢谢@ikegami的评论。我有点困惑。如何正确使用$^I
?这是我第一次听说这个。或者你能给我指一些我可以查阅的参考文章吗?:)-i
逐字添加$^i=''代码>。问题是,您可能已经习惯于将它与-p
配对。所以也许你想看看-p
增加了什么。如果在…中提到这一点,我使用的是binmode(STDOUT,“:raw”)代码>不确定这是否会影响$^I=''代码>你不应该使用标准输出,所以这是不好的binmode(select())
循环内部应该可以工作,但是.Re“我没有找到如何在循环之前设置binmode”,您不能。您可以使用使用open':std',':encoding(…)'添加:encoding
,但无法告诉使用open
默认为“二进制”句柄
unshift(@ARGV, '-') unless @ARGV;
while ($ARGV = shift) {
open(ARGV, $ARGV);
while (<ARGV>) {
... # code for each line
}
}
my $fn = 'test.dat';
open ( my $fh, '<:raw', $fn ) or die "Could not open file '$fn': $!";
unlink $fn or die "$!";
open ( my $fh2, '>:raw', $fn ) or die "Could not reopen file '$fn': $!";
while(<$fh>) {
# Do the substitutions on $_ here ...
print $fh2 $_;
}
close $fh;
close $fh2;