Sathish Kumar
Sathish Kumar

Reputation: 2536

How can I replace a string in Perl?

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

Upvotes: 5

Views: 21965

Answers (3)

kergma
kergma

Reputation: 171

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

Upvotes: 0

velz
velz

Reputation: 29

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

Upvotes: 1

Deqing
Deqing

Reputation: 14632

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.

Upvotes: 13

Related Questions