Why does adding the Perl /x switch stop my regex from matching?
perl, regex
Solution
The `/x` modifier tells Perl to ignore most whitespace that isn't escaped in the regex.
For example, let's just focus on `apples to get`. You could match it with:
$line =~ /apples to get/
But if you try:
$line =~ /apples to get/x
then Perl will ignore the spaces. So it would be like trying to match `applestoget`.
You can read more about it in perlre. They have this nice example of how you can use the modifier to make the code more readable.
# Delete (most) C comments.
$program =~ s {
/\* # Match the opening delimiter.
.*? # Match a minimal number of characters.
\*/ # Match the closing delimiter.
} []gsx;
They also mention how to match whitespace or `#` again while using the `/x` modifier.
Use of /x means that if you want real whitespace or # characters in the pattern (outside a bracketed character class, which is unaffected by /x), then you'll either have to escape them (using backslashes or \Q...\E ) or encode them using octal, hex, or \N{} escapes.
Problem
I'm trying to match: ``` JOB: fruit 342 apples to get ``` The code matches: ``` $line =~ /^JOB: fruit (\d+) apples to get/ ``` But, when I add the `/x` switch in: ``` $line =~ /^JOB: fruit (\d+) apples to get/x ``` It does not match. I looked into the `/x` switch, and it says it just lets you do comments. I don't know why adding `/x` stops my regex from matching.