Regular Expression Newbie Question

A

ahjiang

Hi all,

I have a few simple question here

$program = "/*Hello world*/ How are you";

$program =~ s {
/\* # Match the opening delimiter.
.*? # Match a minimal number of characters.
\*/ # Match the closing delimiter.
} []gsx;


Output: How are you

I understand im using the s/PATTERN/REPLACEMENT/egimosx this.

1) Why does the above syntax still works. It doesnt follow s///.
2) \* Match the opening delimiter. The opening delimiter in $program is
/* how come \* still matches it?

Appreciate any help.
 
N

niall.macpherson

1) Why does the above syntax still works. It doesnt follow s///.
2) \* Match the opening delimiter. The opening delimiter in $program is
/* how come \* still matches it?

Appreciate any help.


1) You can use almost any char as a delimiter in a substitution (or a
match for that matter) - in most cases you will see s/// but you will
sometimes see different ones being used
From perldoc perlrequick

----------------------------------------------------------------------------------------------------------------------
# convert percentage to decimal
$x = "A 39% hit rate";
$x =~ s!(\d+)%!$1/100!e; # $x contains "A 0.39 hit rate"

The last example shows that "s///" can use other delimiters, such
as
"s!!!" and "s{}{}", and even "s{}//". If single quotes are used
"s'''",
then the regex and replacement are treated as single quoted
strings.
----------------------------------------------------------------------------------------------------------

2) The '\' is escaping the first '*' since '*' is a special character
in a regex. Therefore it is just looking for a match on '*' not '\*' .
Similarly for the second '*'.

Hope this helps
 

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,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top