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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志