Reputation: 175
Is there any technical difference between the following code segments in perl? They seem to behave identical
my $str = "A cat is red";
if($str =~ /cat/) {
print "Matches\n";
}
vs
my $str = "A cat is red";
if($str =~ m/cat/) {
print "Matches\n";
}
The difference in this code is the "m" on line 3. Why would someone omit or not omit the "m"?
Upvotes: 13
Views: 4087
Reputation: 386396
There is no difference.
/.../
is short for m/.../
, just like '...'
is short for q'...'
, and "..."
is short for qq"..."
.
If you're going to use the default delimiter (/
for regex match, '
for single-quoted string literals, and "
for double-quoted string literals), you can omit the leading letter(s).
Specifying the leading letter(s) allows you to change the delimiter.
/.../ m/.../ m!...! m{...} Match operator
'...' q'...' q!...! q{...} Single-quoted string literal
"..." qq"..." qq!...! qq{...} Double-quoted string literal
This can be useful to reduce escaping. For example,
/^http:\/\//
is clearer when written as
m{^http://}
Otherwise, the "m", "q" or "qq" is usually omitted. "s", "tr" and "qw" are not optional.
All of this is documented in perlop.
Upvotes: 11
Reputation: 206841
See the RegExp Quote-Like Operators documentation: they're identical. The m
"version" allows you to use other characters instead of /
as a separator. But apart from that, no difference.
Upvotes: 22