Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

regex

perl

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#?

like image 869
Samiron Avatar asked Oct 18 '12 08:10

Samiron


2 Answers

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/;
like image 154
Barmar Avatar answered Sep 20 '22 00:09

Barmar


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.

like image 38
dan1111 Avatar answered Sep 23 '22 00:09

dan1111