-1

What is the difference between chomp and trim in Perl? Which one is better to use and when?

serenesat
  • 4,611
  • 10
  • 37
  • 53
Sam 333
  • 61
  • 2
  • 8
  • 8
    There is no trim function in Perl. Which module are you talking about? –  Jul 07 '15 at 07:58

3 Answers3

4

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;
serenesat
  • 4,611
  • 10
  • 37
  • 53
1

trim removes both leading and trailing whitespaces, chomp removes only trailing input record separator (usually new line character).

Muhammad Soliman
  • 529
  • 5
  • 17
-1

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

serenesat
  • 4,611
  • 10
  • 37
  • 53
QASource
  • 65
  • 1
  • 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
  • 6
    Pedantically, `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