Reputation: 405
Is there a difference between ($ipAddrResult =~ /Regex/gm) and ($ipAddrResult =~ m/Regex/g) in perl string matching? When I google online I get explanation for second one and not the first one. The file I tried to edit has first condition.
Upvotes: 16
Views: 30473
Reputation: 1437
In the expression
/Regex/gm
The "m" stands for multi-line matching. In the expression:
m/Regex/g
The "m" stands for "match" as opposed to a substitution, which looks like this:
s/Regex/replacement/g
Because matching (vs. substitution) is the default, you can generally leave off the "m/" from the start of the expression. In other words "m/Regex/g" is just a synonym for "/Regex/g".
Upvotes: 12
Reputation: 67028
The m
s in different places mean different things.
Let's look at the second example first.
m//
is the regular expression matching operator. As a shortcut, the m
can be omitted, so
$foo =~ m/$pattern/;
is exactly the same as
$foo =~ /$pattern/;
The only time the m
is required is if you want to use delimiters other than /
for your pattern. You can do, for example
$foo =~ m!$pattern!;
or
$foo =~ m[$pattern];
and so on, but these all require the m
to be there.
In the first example, the m
after the regex is a modifier flag which tells the regex how to behave. The regex flags are documented in the perlre man page, which has this to say:
m - Treat string as multiple lines. That is, change "^" and "$" from matching the start or end of line only at the left and right ends of the string to matching them anywhere within the string.
So this:
$foo =~ /$pattern/m;
is the same as this:
$foo =~ m/$pattern/m;
and the same as this:
$foo =~ m{$pattern}m;
Upvotes: 11
Reputation: 189679
Yes, m/regex/g
is syntactically equivalent to just /regex/g
. That is, it doesn't activate the /m
flag at all. Compare to s/foo/bar/
which is not at all the same as s/foo/bar/s
. The name m
stands for "match" I believe.
Upvotes: 3