3

What is the purpose and advantages of chomp function. What all can it do? Does using chomp creates any problems? or using chomp after file opening is necessary?

VAR121
  • 512
  • 2
  • 5
  • 16

3 Answers3

11

chomp is used to remove the $/ variable which is set to mostly \n (new line).

$/ is the input record separator, newline by default.

chomp: It returns the total number of characters removed from all its arguments. It's often used to remove the newline from the end of an input record.

Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
6

chomp simply removes the newline (actually $/) from the end of a string if it is there. It's useful when reading lines from a file (for example) where you want the newline gone, but can still be used on strings that don't have the newline.

It's basically similar to:

chop if /\n$/;

See http://perldoc.perl.org/functions/chomp.html for more detail.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2

chomp removes the newline characters (if any) from the end of a line of text. It is useful because, then you don't have to worry about the particular way that your input represents newlines--Perl handles the details for you.

When should you use it? Whenever you need to remove trailing newlines! Reading data from a text file is the most common case.

dan1111
  • 6,576
  • 2
  • 18
  • 29