1. Perl
  2. builtin functions
  3. here

chomp function - remove a line break

You can use the chomp function to remove a line break at the end of the line.

# Remove a line break at the end of the line
chomp $line;

Remove a line break independent of OS

Note that chomp is OS dependent. For example, when running on Windows, the trailing "\x0D\x0A" is removed, but when running on a Unix-like OS, "\x0A" is removed. \x0D is a escape sequence for carriage return and \x0A is a escape sequence for line feed. On Windows, the line break character is represented by "\x0D\x0A", and on Unix it is represented by "\x0A". This is the value of predefined variable $/ which depends on OS.

For this reason, if the Perl program is saved on Windows and the program is moved to Linux. A line break may not be removed correctly. If you want to remove a line break independent of the OS, use regular expression as follows.

# Remove a line break at the end of the line independent of OS
$string =~ s/\x0D?\x0A?$//;

Example

This is an example using the chomp function.

use strict;
use warnings;

my $message = "I like a cake.\n";

# Remove a line break at the end of the line
chomp($message);
print $message;

Related Informatrion