删除尾随换行符
函数 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
你还可以同时发送多个字符串:
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
但通常情况下,没有人担心删除了多少换行符,因此通常在 void 上下文中看到 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