6

Modifying a Perl script, i got this:

$var =~ s,/$,,;

it seems to be a regex pattern, but i was expecting to found "/" (or "|") instead of "," as separator.

So the question is: when and why one should use in a regex pattern "/" or "|" or ","?

Filippo Lauria
  • 1,965
  • 14
  • 20

2 Answers2

10

In Perl, in the substitution operator, as well as many other operators, you can substitute the delimiter for almost any punctuation character, such as

s#/$##
s=/$==
s!/$!!

Which one to use when is a matter of what you need at the time. Preferably you choose a delimiter that does not conflict with the characters in your regex, and one that is readable.

In your case, a different delimiter from / was used because one wanted to include a slash in the regex, to remove a trailing slash. With the default delimiters, it would have been:

s/\/$//

Which is not as easy to read.

Like I mentioned above, you can do this with a great many operators and functions:

m#...#
qw/.../
qw#...#
tr;...;;
qq?...?
TLP
  • 66,756
  • 10
  • 92
  • 149
  • not just punctuation characters: letters work too: `"foo" =~ s ofoor` → `oo`. However, there is no justification to ever do this (obfuscation aside). – amon Jan 24 '14 at 16:31
  • @amon Indeed. I seem to recall someone using space once, but can't recall how. But perhaps not something to recommend. – TLP Jan 24 '14 at 17:39
3

In Perl, the default regular expression delimiter is /.

However, other characters may be used instead of /. Typically, you would use alternate delimiters when the regular expression itself includes a /. Using alternate delimiters avoids excessive escaping of the delimiter:

s/foo\/bar\//baz/;

vs.

s|foo/bar/|baz|;

perlpdoc perlop:

This is particularly useful for matching path names that contain "/", to avoid LTS (leaning toothpick syndrome).

toolic
  • 57,801
  • 17
  • 75
  • 117