Perl删除尾随的换行符
示例
该函数chomp将从传递给它的每个标量中删除一个换行符(如果存在)。chomp将使原始字符串变异,并返回删除的字符数
my $str = "Hello World\n\n"; my $removed = chomp($str); print $str; # "Hello World\n" print $removed; # 1 # chomp again, removing another newline $removed = chomp $str; print $str; # "Hello World" print $removed; # 1 # chomp again, but no newline to remove $removed = chomp $str; print $str; # "Hello World" print $removed; # 0
您也可以chomp一次输入多个字符串:
my @strs = ("Hello\n", "World!\n\n"); # one newline in first string, two in second my $removed = chomp(@strs); # @strs is now ("Hello", "World!\n") print $removed; # 2 $removed = chomp(@strs); # @strs is now ("Hello", "World!") print $removed; # 1 $removed = chomp(@strs); # @strs is still ("Hello", "World!") print $removed; # 0
但是通常,没有人担心删除了多少换行符,因此chomp通常在空上下文中看到,并且通常是由于从文件中读取了行:
while (my $line = readline $fh) { chomp $line; # now do something with $line } my @lines = readline $fh2; chomp (@lines); # remove newline from end of each line