24

Which characters can be used as delimiters for a Perl regular expression? m/re/, m(re) and måreå all seem to work, but I'd like to know all possibilities.

tchrist
  • 76,727
  • 28
  • 123
  • 176
Tim
  • 13,584
  • 10
  • 64
  • 100

4 Answers4

29

From perlop:

With the m you can use any pair of non-whitespace characters as delimiters.

So anything goes, except whitespace. The full paragraph for this is:

If "/" is the delimiter then the initial m is optional. With the m you can use any pair of non-whitespace characters as delimiters. This is particularly useful for matching path names that contain "/", to avoid LTS (leaning toothpick syndrome). If "?" is the delimiter, then the match-only-once rule of ?PATTERN? applies. If "'" is the delimiter, no interpolation is performed on the PATTERN. When using a character valid in an identifier, whitespace is required after the m.

Mat
  • 195,986
  • 40
  • 382
  • 396
6

As is often the case, I wonder "can I write a Perl program to answer that question?".

Here is a pretty good first approximation of trying all of the printable ASCII chars:

#!/usr/bin/perl
use warnings;
use strict;

$_ = 'foo bar'; # something to match against

foreach my $ascii (32 .. 126) {
    my $delim = chr $ascii;
    next if $delim eq '?'; # avoid fatal error

    foreach my $m ('m', 'm ') {  # with and without space after "m"
        my $code = $m . $delim . '(\w+)' . $delim . ';';
#        print "$code\n";
        my $match;
        {
            no warnings 'syntax';
            ($match) = eval $code;
        }
        print "[$delim] didn't compile with $m$delim$delim\n" if $@;
        if (defined $match and $match ne 'foo') {
            print "[$delim] didn't match correctly ($match)\n";
        }
    }
}
tadmc
  • 3,654
  • 15
  • 14
5

Just about any non-whitespace character can be used, though identifier characters have to be separated from the initial m by whitespace. Though when you use a single quote as the delimiter, it disables interpolation and most backslash escaping.

ysth
  • 92,097
  • 6
  • 117
  • 207
5

There is currently a bug in the lexer that sometimes prevents UTF-8 characters from being used as a delimiter, even though you can sneak Latin1 by it if you aren't in full Unicode mode.

Laurel
  • 5,771
  • 12
  • 29
  • 54
tchrist
  • 76,727
  • 28
  • 123
  • 176
  • any specific chars? `use utf8; ...; $str =~ m ê ê;` works as expected here within an UTF-8 encoded script. – Mat Apr 24 '11 at 13:28
  • @Mat, note that that's a latin-1 character. – Tim Apr 24 '11 at 13:52
  • 2
    `$str =~ m ش ش` parses (and works) too, and that's not latin1 (arabic iso-8859-6). – Mat Apr 24 '11 at 13:54
  • @Mat, I don’t have time to show you the example bugs right now, but they do exist. I bumped into them again a couple of day ago, but I have to run right now. – tchrist Apr 24 '11 at 15:13