用于匹配文件中的字符串的perl语法

时间:2013-11-15 17:51:59

标签: regex string perl matching

我一直在努力学习perl语法。我正在努力学习如何对另一个项目的源代码进行大的条件替换,但一直遇到麻烦。我写了一个简单的脚本来测试我的问题,而且它运行良好。我在一个文件上尝试了它,它不再有效。该文件包含与我的测试字符串相同的文本。

我想我必须在文件中做一些特别的阅读,但我不知道是什么。

test.sh:

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


my $matching = 'Logger\.getInstance\(\)\.addEntry\(((.|\n)*),((.|\n)*),((.|\n)*),((.|\n)*)\)';
my $replacement = '"Logger\.getInstance\(\).addEntry\($1,$7\)"';

my $test_str = "Logger\.getInstance\(\)\.addEntry\(\"error\", \"Thing2D\.PATH_TYPE\", new Object\(\) \{\}\.getClass\(\)\.getEnclosingMethod\(\)\.getName\(\), \"New PATH_TYPE was added and not filled in\.\");";


print "----\nstring:\n" . $test_str . "\n\nreplaced:\n\n";

$test_str =~ s/$matching/$replacement/ee;
print "\n\n" . $test_str . "\n\n\n";


die qq[Usage: perl $0 <subject_file>\n] unless @ARGV == 1;

open my $fh_subject, qq[<], shift @ARGV or die qq[Cannot open input file: $!\n];

my $subject_content;
{
    local $/ = undef;
        $subject_content = <$fh_subject>;
}

print "----\nString:\n" . $subject_content . "\n\nreplaced:\n\n";

$subject_content =~ "s/$matching/$replacement/ee";
print $subject_content;

的test.txt:

Logger.getInstance().addEntry("error", "Thing2D.PATH_TYPE", new Object() {}.getClass().getEnclosingMethod().getName(), "New PATH_TYPE was added and not filled in.");

和命令行:

./test.sh test.txt

感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

$subject_content =~ s/$matching/$replacement/ee;

而不是

$subject_content =~ "s/$matching/$replacement/ee";