$ and Perl global regex modifier

I finally figured out how to add text to the end of each line in a file:

perl -pe 's/$/addthis/' myfile.txt

However, since I am trying to learn Perl to use regular expressions frequently, I cannot understand why the following perl command appends the text “addthis” to the end and starts each line:

perl -pe 's/$/addthis/g' myfile.txt

I thought "$" matches the end of the line no matter what modifier was used to match the regex, but I think this is wrong?

+5
source share
3 answers

:. , /g, . /g , ( ).

/m $ ( ), . , "foo" "foo\n", $ foo. "foo\nbar", , bar, .

/g , $ -

s/$/X/g;

, "foo\n", "fooX\nX".

: /m $ , ,

s/$/X/mg;

"foo\nbar\n" "fooX\nbarX\nX".

+10

, $ , \n ( /m). (. perlre Perldoc. g .

Perl (.. Perl , ) , Perl.

  • , chomp, . g.

  • , Linux/Mac, Windows. \r, \n. , \r chomp. ,

:

open my $file_handle, "<:crlf", $file...

\r\n \n, Windows Linux/Mac. Linux/Mac, . - Windows ( !).

, chomp :

$cat file
line one
line two
line three
line four
$ perl -pe 'chomp;s/$/addthis::/g`
line oneaddthis::line twoaddthis::line threeaddthis::line fouraddthis::

Chomp \n, , . ...

$ perl -pe 'chomp;s/$/addthis/g;print "\n";
line oneaddthis
line twoaddthis
line threeaddthis
line fouraddthis

! .


- , 12 Perl Best Practices:

\A \z .

/m, ^ $ - . , , ^ $ Perl 1. , ? , , ? Perl , " " " ":\A \z ( A, z). "/ " , /m. "/ " , ^ $mean.

Conaway :

perl -pe 's/\z/addthis/mg' myfile.txt

, addthis ​​ :

$cat file
line one
line two
line three
line four
$ perl -pe `s/\z/addthis/mg` myfile.txt
line one
addthisline two
addthisline three
addthisline four
addthis

, . addthis !... \n .

. (, , . , , , , ).

, , Python.


1. , ^ $ Perl? , , I. Perl . , . ( : $, -, , .)

+5

:

perl -pe 's/\n/addthis\n/' 

no gmodifier needed : the regular expression is processed line by line.

0
source

All Articles