简体   繁体   中英

Perl regular expression substitution changes only first letter of each line

I am having trouble doing the simplest of Perl REGEX. It is working correctly in Notepad++ but not Perl.

open FILE, "Something.txt";
while (<FILE>) {
   s/./f/;
    print;
}

However the output only changes the first letter of each line to F. When this regular expression is clearly saying change every character to F!

我已经有一段时间没有使用过perl了,但是尝试s/./f/g (根据Quentin的评论(感谢),g使它成为全局的,而不是在第一次比赛之后停止)。

您需要添加g修饰符以使其成为全局变量,否则它将在第一个匹配项后停止。

s/./f/g

See the following sample code :

The fle :

$ cat /tmp/test
aaaa
bbbb
cccc

The Perl code (I use perlconsole )

Perl> open FH, "<", "/tmp/test"
1

Perl> while (<FH>) { s/./f/g; print; }
ffff
ffff
ffff


Perl> close FH
1

Perl> 

The g modifier in the substitution means all occurrences, see http://perldoc.perl.org/perlre.html#Modifiers

You need to flag it for global change:

open FILE, "Something.txt";
while (<FILE>) {
   s/./f/g;
    print;
}
CLOSE (FILE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM