Why does "perl -pe" / $ / \ n / g`` add 2 empty lines?

I am working on one liner book and stumbled upon

perl -pe 's/$/\n/' file

which inserts an empty line after each line, setting the end of the line to a new line, thereby adding a new line to an existing new line, resulting in an empty line. Since this is the first example without gat the end of the template, I tried

perl -pe 's/$/\n/g' file

this results in two empty lines between the lines.
I would not expect any difference, since there is only one $per line, so replacing all of them should be the same as replacing only the first.
What's going on here?

+4
source share
2 answers

/$/matches "end of line". It could be

  • (, /\z/),
  • (, /(?=\n\z)/).

( , /$/m " ".

  • ,
  • (, /(?=\n)/).

).

/$/\n/g : , :

  • :

    "foo\n"
    #   ^ match
    

    :

    "foo\n\n"
    #     ^ insert before
    
  • :

    "foo\n\n"
    #       ^ match
    

    ​​ :

     "foo\n\n\n"
     #         ^ insert before
    
  • .

: $ DWIMmy , \z \n, , lookaheads, (?=\n). Unicode \R \n.

+9

. $ -

  • /m, , ,

\z : -

",

"" ​​ , , , .

my $s = "xxx\n"

say pos($s) while $s =~ /$/g

3
4

. , ,

s/$/\n/g : /$/, ,

,

  • , , s/\z/\n/ $s .= "\n"

  • , , , , s/\n+\z/\b\n/

, \z , $

\R, - . : CR, LF CRLF

, . , ,

+2

Source: https://habr.com/ru/post/1693368/


All Articles