Juerd wrote:
> Robin Bowes skribis 2006-06-20 13:01 (+0100):
>> Also, Conway recommends always using the /x /m /s flags, so the above
>> regex would be:
>> /\A \d+ \z/xms
>> I unreservedly recommend this book.
>
> Let's not discuss this in too much detail,
Heh, you hope. :)
> but my strong opinion is that
> including /xms by default is a very bad idea. Use them when you *need*
> them, and only then.
Why do you think that?
Conway's reasoning is as follows:
Always use the /x flag
======================
Meaning: ignore whitespace
Rationale: It allows regular expressions to be laid out and annotated in
a maintainable manner. e.g.:
m{'[^\\']*(?:\\.[^\\']*)*'}
vs.
m{ ' # an opening single quote
[^\\']* # any non-special chars
(?: # then all of...
\\ . # any explicitly backslashed char
[^\\']* # followed by anoy non-special chars
)* # ...repeated zero or more times
' # a closing single quote
}x
It is good practice to *always* use this flag, even for simple
expressions as, like all forms of code, regular expressions tend to grow
in complexity and will therefore need a /x eventually.
By always using /x, you will never have to think about it again - all
your regexes will use it.
Always use the /m flag
======================
Meaning: make ^ and $ match at the beginning/end of each line instead of
the perl default which is beginning/end of the whole string.
Rationale: Almost all of the Unix utilities that use regular expressions
(sed, grep, awk) are line-oriented, i.e. ^ and $ naturally mean match
at the begining/end of any line.
The /m flag makes perl behave in the same way.
Always use the /s flag
======================
Meaning: make . match newline
Rationale: It is easy to forget that the dot metacharacter doesn't by
default match *any* character - it doesn't match newlines.
The /s flag corrects this.
Which parts of this advice do you disagree with, and why?
R.