Krab
Krab

Reputation: 6756

Perl - how to put escape sequence into string?

I am converting one form of regex to Perl-compatible regex. I need to replace all occurrences of %s to \s, so I am doing:

$s =~ s/(?<!%)%s/\s/g;

But it gives me error: Unrecognized escape \s passed through at ..... Actually I am understanding where the problem is, so probably I can’t convert to string some unknown escape sequence. But how do I bypass this thing?

Upvotes: 1

Views: 2501

Answers (1)

Ask Bj&#248;rn Hansen
Ask Bj&#248;rn Hansen

Reputation: 6943

You just need to escape the \, like:

$s =~ s/(?<!%)%s/\\s/g;

For example

my $s = "this is a %s test with two %s sequences, the last one here %%s not changed";
$s =~ s/(?<!%)%s/\\s/g;
print "$s\n";

prints

this is a \s test with two \s sequences, the last one here %%s not changed

(not sure if you need the %%s to end up being just %s, if so it needs a little tweak or a second regexp to do that).

Upvotes: 3

Related Questions