-1

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 ?

8bra1nz
  • 697
  • 6
  • 18
  • Possible duplicate of [Reference - What does this regex mean?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – Tushar Feb 28 '17 at 06:53
  • `^`: Start of line, ` *` means any number of spaces, `$`: End of Line. – Tushar Feb 28 '17 at 06:54
  • `$` doesn't match any character as far as I know, that doesn't include `\n`. Or does it ? – 8bra1nz Feb 28 '17 at 06:55
  • you are correct; `$` is always a zero-width match; it does not match a `\n`. But it can match before one. – ysth Feb 28 '17 at 07:04

1 Answers1

5

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

ysth
  • 88,068
  • 5
  • 112
  • 203
  • Thanks that clarified things. Everywhere they say it's just "end of line" and I got the wrong idea. – 8bra1nz Feb 28 '17 at 07:03
  • 2
    @nikachx, Be careful of what documentation you read. There are many regex engine, and they all have their differences. For example, `$` is indeed the end of linestring in some other engines. In Perl, that's `\z`. In Perl, `$` is equivalent to `(?=\n\z|\z)` (without the `m` modifier) or `(?=\n|\z)` (with the `m` modifier). – ikegami Feb 28 '17 at 07:31
  • @ikegami I am reading `Advanced Regular Expressions` of O`Relly. It is't really a reference I just came up with this expression that worked unexpectedly. – 8bra1nz Feb 28 '17 at 07:47