Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex Perl就地替换_Regex_Perl - Fatal编程技术网

Regex Perl就地替换

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 ($

在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 ($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;