Josh Greifer
Josh Greifer

Reputation: 3231

What does it mean when a regex is delimited by colons?

What function do the colons serve in this Perl regex that I found in some production code?

if ($r->uri =~ m:/copy/(\d+):) {
    my $ref = $1;

The code is parsing a URI and the second line uses the captured group.

Upvotes: 2

Views: 173

Answers (2)

yoniyes
yoniyes

Reputation: 1030

After the m, any character can act as the delimiter, so the colons are replacing the standard /s and lets them become a normal character.

From perlrequick:

the // default delimiters for a match can be changed to arbitrary delimiters by putting an 'm' out front

Upvotes: 6

redneb
redneb

Reputation: 23870

The m operator in perl is used to test a string against a regular expression. You typically use it like that:

"string" =~ m/regex/

If you want, you can change the quoting character (/ in the above example). So the above example can be equivalently written as any of the following:

"string" =~ m(regex)
"string" =~ m[regex]
"string" =~ m{regex}
"string" =~ m|regex|
"string" =~ m:regex:

Note that if you use /, then you can omit the m, as in

"string" =~ /regex/

Upvotes: 10

Related Questions