如何在Perl正则表达式/替换中使用变量?

时间:2019-06-06 21:03:55

标签: regex perl variables replace

基本上,我试图在文本文件中插入一行,并且生成一个系统命令来执行“ perl -pi.orig -e”

这就是我想要做的:

my $find='# Foo Bar'
my $replace="foo/bar/blah.txt\n# Foo'

my $file = './some_text_file.txt'

system("perl -pi.orig -e 's|$find|$replace|;' $file");

此方法无需使用变量即可。

$ file中包含以下文本:

# Foo Bar is a comment
then/a/path/to/a/file.txt

3 个答案:

答案 0 :(得分:5)

不要从Perl调用Perl,直接在一个过程中完成工作。

#! /usr/bin/perl
use warnings;
use strict;

my $find    = qr/# Foo/;
my $replace = "foo/bar/blah.txt\n# Foo";
my $file    = './some_text_file.txt';

open my $in, '<', $file or die $!;
open my $out, '>', "$file.new" or die $!;

while (<$in>) {
    s/$find/$replace/;
    print {$out} $_;
}
close $out;
rename "$file.new", $file or die "Can't rename";

或者,如果您需要保留备份,

rename $file, "$file.backup" or warn "Can't create backup";
rename "$file.new", $file or die "Can't rename";

答案 1 :(得分:1)

当您要在程序中使用单行代码时,use Deparse来查看需要执行的操作:

$ perl -MO=Deparse -pi.orig -e 's|$find|$replace|;' file
BEGIN { $^I = ".orig"; }
LINE: while (defined($_ = readline ARGV)) {
    s/$find/$replace/;
}
continue {
    die "-p destination: $!\n" unless print $_;
}
-e syntax OK

从那里您可以看到您需要做什么。

choroba's answer执行相同的操作,但没有特殊变量$^I进行文件处理。

答案 2 :(得分:0)

我们还可以使用一个简单的正则表达式,并将其替换为我们想要的任何东西:

Demo

测试

use strict;

my $str = 'foo/bar/blah.txt\\n# Foo';
my $regex = qr/#\sFoo/mp;
my $subst = 'With Anything You wish To Replace';

my $result = $str =~ s/$regex/$subst/rg;

print $result\n";