Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subsitute with variable options in perl script

Tags:

replace

perl

In perl text substitutions are very simple and powerful. I want to do a script with variable substitutions, like:

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

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

Results in:

Scalar found where operator expected ...

Is there a posibility to do the option variable?

like image 439
Horst Avatar asked Nov 30 '17 08:11

Horst


People also ask

How do I replace a variable in Perl?

print $url if $url =~ s/$search/$replace/ee; This will give us: Port and host name lower case.

What is $@ in Perl?

$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.

What is $_ in Perl script?

The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }

How do I replace a section of a string in Perl?

Perl: Use s/ (replace) and return new string [duplicate]


1 Answers

Since you're using /g in all cases you can,

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

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

More on this subject in 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.

like image 106
mpapec Avatar answered Nov 18 '22 15:11

mpapec