gpt4 book ai didi

regex - Perl 就地替换

转载 作者:行者123 更新时间:2023-12-02 00:50:59 26 4
gpt4 key购买 nike

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

}

我们如何就地保存所有更改行?

因为我需要在就地更改 html 源后立即使用 XML::LibXML 对 html 文件进行快速验证..

提前致谢。

最佳答案

你可以尝试这样的事情:

my $filename = 'test.dat';
@ARGV = ($filename);
$^I = '';
while(<<>>) {
binmode(ARGV, ':raw');
# Do the substitiution on $_ here ...
print;
}

我没有找到如何设置 binmode在循环之前,因为 ARGV仅在 <> 之后定义运算符已被使用。

  • $^IARGV变量在 perlvar 中描述

  • 参见 perlop有关为什么应该使用 <<>> 的信息而不是 <> .

一些注意事项:

  • while(<>) { ... }根据perlop , 循环
while (<>) {  ...         # code for each line
}

is equivalent to the following Perl-like pseudo code:

unshift(@ARGV, '-') unless @ARGV;   
while ($ARGV = shift) {
open(ARGV, $ARGV);
while (<ARGV>) {
... # code for each line
}
}
  • 在没有备份文件的情况下使用就地编辑:$^I="" :

根据 perlrun :

If no extension is supplied, and your system supports it, the original file is kept open without a name while the output is redirected to a new file with the original filename. When perl exits, cleanly or not, the original file is unlinked.

更多信息请见this博客:

Perl opens and immediately unlink()s the original file, then opens a new file with the same name (new file descriptor and inode), and sends output to this second file; at the end, the old file is closed and thus deleted because it was unlinked, and what's left is a changed file with the same name as the original.

另见 doio.c用于实际实现。

  • 根据以上内容,以下可能有效:

    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;

关于regex - Perl 就地替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57703666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com