Using the Perl chomp() function
Introduction
The chomp()
function will remove (usually) any newline character from the end of a string. The reason we say usually is that it actually removes any character that matches the current value of $/ (the input record separator), and $/ defaults to a newline.
For more information on the $/ variable, try perldoc perlvar
and see the entry for $/.
Example 1. Chomping a string
Most often you will use chomp()
when reading data from a file or from a user. When reading user input from the standard input stream (STDIN) for instance, you get a newline character with each line of data. chomp()
is really useful in this case because you do not need to write a regular expression and you do not need to worry about it removing needed characters.
When running the example below, using the enter key on a line by itself will exit the program.
Example usage and output of this program is:
Example 2. Chomping an array
If you chomp an array, it will remove a newline from the end of every element in the array:
This program produces the following output:
As you can see, the newlines have been removed from “bob” and “fred”, but no characters have been removed from “jill”.
Example 3. Chomping a hash
If you pass a hash into chomp()
, it will remove newlines from every value (not key) of the hash:
This program outputs: