[PATTERN MATCHING]

J

J. Romano

Nicolas said:
Let's say that I have this:

$line =~ s/$pattern/$replacement/;

It should find every $pattern in $line and replace it by $replacement
right?

No. It will replace only the first occurrence of $pattern (if at
least one exists) with $replacement. To replace every occurrence, use
the /g switch, like this:

$line =~ s/$pattern/$replacement/g;
But since I have characters such as "|", """, "'", "!", "?"
in my strings, it has a very strange behavior.

Is there any way to specify perl NOT TO USE regular expressions
expressions in my example?

Yes. Others posters have (correctly) said:

$line =~ s/\Q$pattern\E/$replacement/;

but you can also "backslash" the special characters (like "|", """,
"'", "!", "?") with the quotemeta() function. This function will
return a new pattern that you can use that has all the special
characters escaped (so that they won't interfere with the regular
expression matching). You use it like this:

my $escapedPattern = quotemeta($pattern);
$line =~ s/$escapedPattern/$replacement/g;

In other words, if you have the line:

print quotemeta("Again? (y/n)");

you'll see the output:

Again\?\ \(y\/n\)

meaning that if you use that output in a pattern match, the "?", "(",
and ")" characters won't affect how you match a pattern.

Note that, according to "perldoc -f quotemeta", the line:

my $escapedPattern = quotemeta($pattern);

is equivalent to:

my $escapedPattern = "\Q$pattern\E";

which makes the following regular expression substitutions equivalent:

my $escapedPattern = quotemeta($pattern);
$line =~ s/$escapedPattern/$replacement/g;

$line =~ s/\Q$pattern\E/$replacement/g;

Which method should you use? In my opinion, you should use
whichever one you find more readable and easier to understand. And of
course, that part depends on you.

I hope this helps, Nicolas.

-- Jean-Luc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top