Why do blank lines match this regex?
G'day,
I am using the following Perl snippet to extract output from a Solaris cluster command.
open(CL,"$clrg status |");
my @clrg= grep /^[[:lower:][:space:]]+/,<CL>;
close(CL);
I get the following when I print the contents of the @clrg BTW array elements "=>" and "<=" the line separators are inserted into my print statement:
=><= =>nas-rg mcs0.cwwtf.bbc.co.uk No Online<= => mcs1.cwwtf.bbc.co.uk No Offline<= =><= =>apache-rg mcs0.cwwtf.bbc.co.uk No Online<= => mcs1.cwwtf.bbc.co.uk No Offline<= =><=
When I replace it with the following Perl snippet, the blank lines don't match.
open(CL,"$clrg status |");
my @clrg= grep /^[[:lower:][:space:]]{3,}/,<CL>;
close(CL);
And I get the following:
=>nas-rg mcs0.cwwtf.bbc.co.uk No Online<= => mcs1.cwwtf.bbc.co.uk No Offline<= =>apache-rg mcs0.cwwtf.bbc.co.uk No Online<= => mcs1.cwwtf.bbc.co.uk No Offline<=
Simple question: why?
BTW Using {1,} in the second Perl snippet also matches blank lines!
Any suggestions are greatly appreciated!
amuses,
a source to share
This will have to do with what [:space:]
matches newlines and carriage returns.
So, [[:space:]]+
will match \n
, \r\n
or \n\n
.
But [[:space:]]{3,}
it will take three characters and an empty string is easy \n
.
{1,}
and +
mean the same thing: match the previous group one or more times.
PS Typical newline \n
on Unix and \r\n
Windows.
a source to share
Hm. According to the Perl regex documentation , the character class [:space:]
should not contain newlines, as it is assumed to be equivalent \s
(except that it recognizes an extra character, a vertical tab to maintain POSIX compliance).
However, by just testing this on 5.10.0, I can check if it matches newlines as well. Whether it's a bug in Perl or in the documentation, I'll post for Perl maintainers. But to avoid the immediate problem, use the previous solution for the responder and just use the \s
POSIX class instead.
a source to share