Samiron
Samiron

Reputation: 5317

Difference between Perl regular expression delimiters /.../ and #...#

Today I came across two different syntaxes for a Perl regular expression match.

#I have a date string
my $time = '2012-10-29';

#Already familiar "m//":
$t =~ m/^(\d{4}-\d\d-\d\d)$/

#Completely new to me m##.
$t =~ m#^(\d{4}-\d\d-\d\d)#/

Now what is the difference between /expression/ and #expression#?

Upvotes: 8

Views: 2262

Answers (5)

dan1111
dan1111

Reputation: 6566

Perl allows you to use pretty much any characters to delimit strings, including regexes. This is especially useful if you need to match a pattern that contains a lot of slash characters:

$slashy =~ m/\/\//;   #Bad
$slashy =~ m|//|;   #Good

According to the documentation, the first of those is an example of "leaning toothpick syndrome".

Most but not all characters behave in the same way when escaping. There is an important exception: m?...? is a special case that only matches a single time between calls to reset().

Another exception: if single quotes are used for the delimiter, no variable interpolation is done. You still have to escape $, though, as it is a special character matching the end of the line.

Upvotes: 8

Barmar
Barmar

Reputation: 781868

As everone else said, you can use any delimiter after the m.

/ has one special feature: you can use it by itself, e.g.

$string =~ /regexp/;

is equivalent to:

$string =~ m/regexp/;

Upvotes: 9

GarethL
GarethL

Reputation: 1493

There is no difference; the "/" and "#" characters are used as delimiters for the expression. They simply mark the "boundary" of the expression, but are not part of the expression. In theory you can use most non-alphanumeric characters as a delimiter. Here is a link to the PHP manual (It doesn't matter that it is the PHP manual, the Regex syntax is the same, I just like it because it explains well) on Perl compatible regular expression syntax; read the part about delimiters

Upvotes: 1

user507077
user507077

Reputation:

After the match or search/replace operator (the m and s, respectively) you can use any character as the delimiter, e.g. the # in your case. This also works with pairs of parenthesis: s{ abc (.*) def }{ DEF $1 ABC }x.

Advantages are that you don't have to escape the / (but the actual delimiter characters, of course). It's often used for clarity, especially when dealing with things like paths or protocols.

Upvotes: 3

Quentin
Quentin

Reputation: 944076

Nothing except what you have to escape in the regex. You can use any pair of matched characters you like.

$string = "http://example.com/";
$string =~ m!http://!;
$string =~ m#http://!#;
$string =~ m{http://};
$string =~ m/http:\/\//;

Upvotes: 3

Related Questions