|
|
Tutorials

Perl

|
Topic |
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:\programfiles\perl\bin\perl
print "content-type: text/html\n\n";
$string = "my name is sam anderson\n";
$string2 ="newline";
chomp($string);
print $string;
print $string2;
print"<br>";
@arr= ("sam", "jill\n", "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:\programfiles\perl\bin\perl
print "content-type: text/html\n\n";
%name = ('first' => "one\n",'Peter' => "two\n");
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.
|
|
A Note |
|
Simple introduction, basic CGI perl programming codes with examples.
Do send your feedback or suggestions on this tutorial.
This is a copyright content.
|
|
|
|