I couldn't figure out how to change from /usr/lib to /synopsys/vcs/lib/ by only using $mypath=~s/.....; is there anyway to do it?
$mypath = "/usr/lib";
$mypath =~ s/usr/synopsys/lib//g;
print "$mypath\n";```
CodePudding user response:
/
is a special character since it's being used as the delimiter. If therefore needs to be escaped.
$mypath =~ s/\/usr\/lib/\/synopsys\/vcs\/lib\//;
However, using an alternative delimiter means we wouldn't need all those escapes.
$mypath =~ s{/usr/lib}{/synopsys/vcs/lib/};
That replaces the first instance of /usr/lib
contained in the string. If you want to replace /usr/lib
when it's the entirety of the string, I'd use
$mypath = "/synopsys/vcs/lib/" if $mypath eq "/usr/lib";
CodePudding user response:
the regex replace works like s/match this / replace with this /
In perl you need to escape the forward slash / with a back slash \
then use parentheses to capture usr\/
into $1
So for your example:
$mypath =~ s/(usr\/)/$1synopsys\//;