刪除尾隨換行符
函式 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