What does Perl's modifier /m = multiline mean?
what does Perl's /m modifier means from this example?
For example, let say I have the following information in the Example.txt text file. And each line ends with the newline character with a 开发者_运维知识库data record of Data The input record separator is set to:
$/="__Data__";
Example.txt
__Data__
This is test A.\n
This is test B.\n
This is test C.\n
This is test D.\n
Question 1, after changing the input record separator to Data, would the ^ and $ characters be position as follow?
^__Data__
This is test A.\n
This is test B.\n
This is test C.\n
This is test D.\n$
Question 2, let say I use the /m modifier while having the input record separator still set to Data, would the ^ and $ characters be set to the following?
^__Data__$
^This is test A.\n$
^This is test B.\n$
^This is test C.\n$
^This is test D.\n$
if(/__Data__/m)
{
print;
}
/$/
is not affected by $/
.
Without /m,
/^/
matches the starts of the string. (/(?-m:^)/
⇔/\A/
)/$/
matches at the end of the string, and before a newline at the end of the string. (/(?-m:$)/
⇔/\Z/
⇔/(?=\n\z)|\z/
)
^__Data__\n "^" denotes where /(?-m:$)/ can match
This is test A.\n "$" denotes where /(?-m:$)/ can match
This is test B.\n
This is test C.\n
This is test D.$\n$
With /m,
/^/
matches the starts of the string and after a "\n". (/(?m:^)/
⇔/\A|(?<=\n)/
)/$/
matches before a newline and at the end of the string. (/(?m:$)/
⇔/(?=\n)|\z/
)
^__Data__$\n "^" denotes where /(?m:^)/ can match
^This is test A.$\n "$" denotes where /(?m:$)/ can match
^This is test B.$\n
^This is test C.$\n
^This is test D.$\n$
I was asked about
...$\n$
First, let's demonstrate:
>perl -E"say qq{abc\n} =~ /abc$/ ? 1 : 0"
1
>perl -E"say qq{abc\n} =~ /abc\n$/ ? 1 : 0"
1
The point is to allow /^abc$/
to match both "abc\n"
and "abc"
.
>perl -E"say qq{abc\n} =~ /^abc$/ ? 1 : 0"
1
>perl -E"say qq{abc} =~ /^abc$/ ? 1 : 0"
1
Your assumption is correct, multiline causes ^ and $ to match the beginning and end of the string, whereas without it you match between newlines (and string ends).
精彩评论