Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace a string in Perl?

Tags:

regex

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

like image 459
Sathish Kumar Avatar asked Jan 07 '23 11:01

Sathish Kumar


2 Answers

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.

like image 160
Deqing Avatar answered Jan 14 '23 17:01

Deqing


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";
like image 21
velz Avatar answered Jan 14 '23 18:01

velz