Ghostff
Ghostff

Reputation: 1458

Add html to perl Regex

Am trying to replace all `` with a HTML code tag

replace:

$string = "Foo `FooBar` Bar";

with:

$string = "Foo <code>FooBar</code> Bar";

i tried these

$pattern = '`(.*?)`';

my $replace = "<code/>$&</code>";
$subject =~ s/$pattern/$replace/im;

#And

$subject =~ s/$pattern/<code/>$&</code>/im;

but none of them works.

Upvotes: 1

Views: 62

Answers (1)

Schwern
Schwern

Reputation: 164889

Assuming you meant $string instead of $subject...

use strict;
use warnings;
use v5.10;

my $string = "Foo `FooBar` Bar";

my $pattern = '`(.*?)`';
my $replace = "<code/>$&</code>";

$string =~ s{$pattern}{$replace}im;
say $string;

This results in...

$ perl ~/tmp/test.plx
Use of uninitialized value $& in concatenation (.) or string at /Users/schwern/tmp/test.plx line 9.
Foo <code/></code> Bar

There's some problems here. First, $& means the string matched by the last match. That would be all of `FooBar`. You just want FooBar which is inside capturing parens. You get that with $1. See Extracting Matches in the Perl Regex Tutorial.

Second is $& and $1 are variables. If you put them in double quotes like $replace = "<code/>$&</code>" then Perl will immediately interpolate them. That means $replace is <code/></code>. This is where the warning comes from. If you want to use $1 it has to go directly into the replace.

Finally, when quoting regexes it's best to use qr{}. That does special regex quoting. It avoids all sorts of quoting issues.

Put it all together...

use strict;
use warnings;
use v5.10;

my $string = "Foo `FooBar` Bar";

my $pattern = qr{`(.*?)`};
$string =~ s{$pattern}{<code/>$1</code>}im;

say $string;

Upvotes: 4

Related Questions