Daniele
Daniele

Reputation: 329

How to use a variable in a substitution?

I've a text file and I want to match and erase the following text (please note the newline):

[ From:
http://www.website.com ]

The following code works

$text =~ s/\[.*\]//ms;

This other doesn't

my $patt = \[.*\];
$text =~ s/$patt//ms;

Would someone be so kind to explain me why? Thanks in advance

Upvotes: 0

Views: 105

Answers (2)

Borodin
Borodin

Reputation: 126722

The only reason your variation isn't working is that you haven't put quotes around your $patt string. As it is it throws a syntax error. This works fine

my $patt = '\[.*\]';
$text =~ s/$patt//ms;

My only comment is that the /m modifier is superfluous as it modifies the behaviour of the $ and ^ anchors, which you aren't using here. Only /s is necessary to make the . match newline characters.

Upvotes: 1

user4035
user4035

Reputation: 23729

The second variant works perfectly, if you quote the pattern string and get rid of syntax error:

#!/usr/bin/perl

use strict;
use warnings;

my $text = qq{a[ From:
http://www.website.com ]b};

my $patt = qr/\[.*?\]/s;
$text =~ s/$patt//;

print $text;

Prints:

ab

I added ? quantifier to the regexp to make the replacement ungreedy. And removed m modifier, because you are not using ^ and $ in your regexp, so m is useless.

Upvotes: 3

Related Questions