如何在perl脚本中替换变量选项

前端之家收集整理的这篇文章主要介绍了如何在perl脚本中替换变量选项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在perl文本中,替换非常简单和强大.
我想做一个带有变量替换的脚本,例如:

if ( $IgnoreCase ) {$opt = "gi"} else {$opt = "g"}

$string =~ s/$source/$replace/$opt;

结果是:

Scalar found where operator expected …

是否有可能做选项变量?

解决方法

因为你在所有情况下都可以使用/ g,

my $opt = $IgnoreCase ? "(?i)" : "";

$string =~ s/$opt$source/$replace/g;

关于这个主题的更多内容perldoc perlre

One or more embedded pattern-match modifiers,to be turned on (or turned off if preceded by “-” ) for the remainder of the pattern or the remainder of the enclosing pattern group (if any).

This is particularly useful for dynamically-generated patterns,such as those read in from a configuration file,taken from an argument,or specified in a table somewhere. Consider the case where some patterns want to be case-sensitive and some do not: The case-insensitive ones merely need to include (?i) at the front of the pattern.

猜你在找的Perl相关文章