Perl Language Strings and quoting methods Removing trailing newlines


Example

The function chomp will remove one newline character, if present, from each scalar passed to it. chomp will mutate the original string and will return the number of characters removed

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    

You can also chomp more than one string at once:

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

But usually, no one worries about how many newlines were removed, so chomp is usually seen in void context, and usually due to having read lines from a file:

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