What is the difference between chomp
and trim
in Perl? Which one is better to use and when?
3 Answers
Chomp: 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 see chomp.
As rightfold has commented There is no trim function in Perl. Generally people write a function with name trim (you can use any other name also) to remove leading and trailing white spaces (or single or double quotes or any other special character)
trim remove white space from both ends of a string:
$str =~ s/^\s+|\s+$//g;

- 4,611
- 10
- 37
- 53
trim removes both leading and trailing whitespaces, chomp removes only trailing input record separator (usually new line character).

- 529
- 5
- 17
-
6trim is not in core module it is in [String::Util](https://metacpan.org/pod/String::Util) – Arunesh Singh Jul 07 '15 at 07:58
Chomp: It only removes the last character, if it is a newline.
More details can be found at: http://perldoc.perl.org/functions/chomp.html
Trim: There is no function called Trim in Perl. Although, we can create our function to remove the leading and trailing spaces in Perl. Code can be as follows:
perl trim function - remove leading and trailing whitespace
sub trim($)
{
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
More details can be found at :http://perlmaven.com/trim
-
Haha I wrote something almost exactly like this a few years ago to trim leading/trailing whitespace. For completeness I also put a `chomp $string;` near the top too :) – thonnor Jul 07 '15 at 09:11
-
6Pedantically, `chomp` doesn't remove a newline, it removes the current value of `$/` (which is usually a newline). – Dave Cross Jul 07 '15 at 09:30