kurotsuki
kurotsuki

Reputation: 4797

Perl regex with exclamation marks

How do you define/explain this Perl regex:

$para =~ s!//!/!g;

I know the s means search, and g means global (search), but not sure how the exclamation marks ! and extra slashes / fit in (as I thought the pattern would look more like s/abc/def/g).

Upvotes: 5

Views: 5670

Answers (3)

TLP
TLP

Reputation: 67900

The substitution regex (and other regex operators, like m///) can take any punctuation character as delimiter. This saves you the trouble of escaping meta characters inside the regex.

If you want to replace slashes, it would be awkward to write:

s/\/\//\//g;

Which is why you can write

s!//!/!g; 

...instead. See http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators

And no, s/// is the substitution. m/// is the search, though I do believe the intended mnemonic is "match".

Upvotes: 4

zellio
zellio

Reputation: 32504

Perl's regex operators s, m and tr ( thought it's not really a regex operator ) allow you to use any symbol as your delimiter.

What this means is that you don't have to use / you could use, like in your question !

# the regex
s!//!/!g

means search and replace all instances of '//' with '/'

you could write the same thing as

s/\/\//\/g 

or

s#//#/#g

or

s{//}{/}g

if you really wanted but as you can see the first one, with all the backslashes, is very hard to understand and much more cumbersome.

More information can be found in the perldoc's perlre

Upvotes: 10

hobbs
hobbs

Reputation: 240344

The exclamation marks are the delimiter; perl lets you choose any character you want, within reason. The statement is equivalent to the (much uglier) s/\/\//\//g — that is, it replaces // with /.

Upvotes: 1

Related Questions