chomp Function in Perl
What is chomp Function in Perl?
Explanation
chomp Function:
This is used to remove newline character "n" from the end of a string, or from end of every element of an array, or from every value of a hash.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
$string = "my name is sam andersonn";
$string2 ="newline";
chomp($string);
print $string;
print $string2;
print"<br>";
@arr= ("sam", "jilln", "fred");
chomp (@arr);
print "@arr";
Result :
my name is sam andersonnewline
sam jill fred
In the first example, the "$string" has a newline character at the end, which is removed, so the two different strings "string", "string2" are printed in the same line.In the second example the array element "jill" has a new line character which is removed so all the array elements are printed in the same line.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
%name = ('first' => "onen",'Peter' => "twon");
chomp(%name);
foreach $key (keys %name)
{
print "$key: $name{$key}";
}
Result :
first: onePeter: two
In the above Perl example the "n" character is removed from all the elements of the array, so that the keys and values are printed in the same line.