5

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'.

6
  • Why not just print "Path is $var1"? What is the substitution supposed to do? Commented Mar 17, 2016 at 3:05
  • That was a example created by me. I need to do similar replacement in 'live script' Commented Mar 17, 2016 at 3:07
  • Been a while since I did perl but isn't $var just going to be treated as a literal string that's part of the regex? Commented Mar 17, 2016 at 3:07
  • Not sure what you want to do. Is it "Path is M4S120_appscan" replace to "Path is SCANS"? Commented Mar 17, 2016 at 3:11
  • @Deqing Yes, I want to replace 'M4S120_appscan" to "SCANS" through variables. That's all Commented Mar 17, 2016 at 3:19

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Does this work if $find or $replace contain special characters? Why not $str =~ s/M4S120_appscan/SCANS/? (maybe with /g to replace all, not just the first match)
1

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";

Comments

0

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";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.