How can I replace a string in Perl?
12,626
Solution 1
The substitution operator, s///
, takes three arguments: the string, in which we want to do replacement, in your example is a $path
variable, the search term ($var
) and the replacement, $var1
.
As you can see, you try to replace "M4S120_appscan" with "SCANS" inside an empty string, because $path is not initialized. You need to initialize $path before doing replacement, for example:
$path = "M4S120_appscan";
Solution 2
To replace "M4S120_appscan" with "SCANS" in a string:
$str = "Path is M4S120_appscan";
$find = "M4S120_appscan";
$replace = "SCANS";
$str =~ s/$find/$replace/;
print $str;
If this is what you want.
Solution 3
Substitution is a regular expression search and replace. Kindly follow Thilo:
$var = "M4S120_appscan";
$var =~ s/M.+\_.+can/SCANS/g; # /g replaces all matches
print "path is $var";
Author by
Sathish Kumar
Updated on June 19, 2022Comments
-
Sathish Kumar almost 2 years
I am trying to do a simple string substitution, but could not succeed.
#!/usr/bin/perl $var = "M4S120_appscan"; $var1 = "SCANS"; $path =~ s/$var/$var1/; print "Path is $path"
The output should be
"Path is SCANS"
, but it prints nothing in 'output'.