gpt4 book ai didi

regex - 使用 <> 和正则表达式搜索和替换文本文件中的元素

转载 作者:行者123 更新时间:2023-12-04 23:58:06 25 4
gpt4 key购买 nike

我正在学习 Perl,第 9 章,“使用正则表达式处理文本”。

这是章末练习中的两个:

  1. Write a program to add a copyright line to all of your exercise answers so far, placing a line like ## Copyright (c) 20XX by Yours Truly in the file immediately after the 'shebang' line. Presume that the program will be invoked with the filenames to edit already on the command line.

  2. Modify the previous program so that it doesn't edit the files that already contain the copyright line. As a hint on that, you might need to know that the name of the file being read by the diamond operator is in $ARGV.



这是我尝试的解决方案:
#!/usr/bin/env perl

use 5.014;
use warnings;

my $shebang = '(#!/usr/bin/env perl|#!/usr/bin/perl)';
my $copyright = '# Copyright (c) 20XX Yours Truly';

$^I = ".bak";

while (<>) {
unless (/$copyright/mi) {
s/($shebang)/$1\n$copyright/mig;
}
print;
}

使用 perl ch9.pl sample_perl_script.pl 在命令行上运行.

我的目标是:
  • 无论路径如何,保持原始shebang完好无损。
  • 循环 <>就一次。
  • 检查版权声明是否存在。
  • 如果没有,请添加它(因此尝试使用 unless { ... } )。

  • 这适用于问题的第一部分(添加版权行),但不适用于第二部分(检查以确保版权不存在)。

    我的问题是:为什么?为什么是 unless当我运行程序时完全被忽略?

    我看了看附录,书中提出的解决方案是创建一个哈希来跟踪来自 $ARGV 的文件名。 , 并将文件传递两次。首先删除已经有版权声明的文件,然后执行搜索/替换。像这样:
    my %do_these;
    foreach (@ARGV) {
    $do_these{$_} = 1;
    }

    while (<>) {
    if (/\A## Copyright/) {
    delete $do_these{$ARGV};
    }
    }

    @ARGV = sort keys %do_these;
    $^I = ".bak";
    while (<>) {
    if (/\A#!/) {
    $_ .= "## Copyright (c) 20XX by Yours Truly\n";
    }
    print;
    }

    这当然有效,但它似乎是工作的两倍。我想看看是否有办法在单个 while (<>) { ... } 中做到这一点循环,用我的方法,并更好地理解菱形运算符的工作原理。

    如果我的方法完全不合时宜,请解释原因,不要顾及我的感受。比起我的自我,我对全面理解更感兴趣。

    最佳答案

    你这本书的方法很愚蠢。实际上,我认为 perl 很糟糕,因为您的版权声明有像 ( 这样的特殊字符。 .

    您要的是quotemeta功能。 Link

    我会像这样改变你的程序:

    while (<>) {
    my $copyright2 = quotemeta $copyright;
    unless (/$copyright2/mi) {
    s/($shebang)/$1\n$copyright/mig;
    }
    print;
    }

    如果这不起作用,请道歉。我已经有一段时间没有写 perl 了。

    关于regex - 使用 <> 和正则表达式搜索和替换文本文件中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14321986/

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