从 shell 执行“perl 命令”并使用系统命令从 perl 脚本执行相同的命令

Ram*_*kar 3 perl escape-characters

我无法照顾特殊字符。

我有以下 perl 脚本。

while(@mapping_array[$i])
{  
  chomp(@mapping_array[$i]);
  my @core= split ( /  / , $mapping_array[$i]) ;
  @core[0] =~ tr/ //ds ;   ## Deleting blank spaces
  @core[1] =~ tr/ //ds ;     
  system("perl -pi -e 's/@core[0]/@core[1]/' $testproc ");  
  print "@core[0] \n";
  print "@core[1] \n";
  $i++;
}
Run Code Online (Sandbox Code Playgroud)

问题是我的@core[0]变量可能是一个简单的字符串,abc比如TEST[1]. 我的脚本按预期工作abc,用 的值替换它@core[1],但如果我的@core[0]是,它会失败TEST[1]

在替换运算符中使用?而不是/没有帮助。我怎样才能正确地做到这一点?

ter*_*don 6

听起来您正在寻找quotemeta. 如中所述perldoc -f quotemeta

quotemeta EXPR
        Returns the value of EXPR with all the ASCII non-"word" characters
        backslashed. (That is, all ASCII characters not matching
        "/[A-Za-z_0-9]/" will be preceded by a backslash in the returned
        string, regardless of any locale settings.) This is the internal
        function implementing the "\Q" escape in double-quoted strings.
Run Code Online (Sandbox Code Playgroud)

因此,您的脚本将是(请注意,数组元素应指定为$foo[N],而不是@foo[N]):

chomp(@mapping_array);
while($mapping_array[$i])
{  
    my @core= split ( /  / , $mapping_array[$i]) ;
    $core[0] =~ tr/ //ds ;   ## // Deleting blank spaces
    $core[1] =~ tr/ //ds ;   # / fix SO highlighting
    my($k,$l)=(quotemeta($core[0]),quotemeta($core[1]))
    system("perl -pi -e 's/$k/$l/' $testproc "); 
    print "$core[0] \n$core[1] \n";
    $i++;
}
Run Code Online (Sandbox Code Playgroud)


cho*_*oba 5

通常可以避免从 Perl 运行 Perl。

for my $both (@mapping) {
    my ($regex, $replace) = split /  /, $both;
    tr/ //ds for $regex, $replace;                                                                   # // Fix SO highlighting bug.

    open my $IN,  '<', $testproc or die $!;
    open my $OUT, '>', "$testproc.new" or die $!;
    while (<$IN>) {
        s/\Q$regex/$replace/;
        print {$OUT} $_;
    }
    close $OUT or die $!;
    rename $testproc, "$testproc.old" or die $!;
    rename "$testproc.new", $testproc or die $!;
}
Run Code Online (Sandbox Code Playgroud)

\Q 对应于quotemeta,它阻止解释 $regex 变量中的特殊字符。