nikachx nikachx -4 years ago 115
Perl Question

Perl match blank lines with m/^ *$/

This is the perl script:

while ($line = <>)
{
if ($line =~ m/^ *$/)
{
$line = "--blank\n";
}
print($line);
}


That replaces all blank lines in file with
--blank\n
.

I don't get why it is working. Why does this regex
m/^ *$/
matches blank lines ? Because there is newline character at the end of line it must not match.

UPDATE:

I assume:
^
is the beginning of line,
*
is no or as many spaces as possible,
$
end of line.

Empty line must be something like this:
[ ][ ][ ]\n
that is
^
then
[ ]*
then
\n
and
$
.

Why do they match ?

Answer Source

$ matches at either the end of a string or before a newline at the end of a string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download