Perl | chomp() Function
Last Updated :
13 Apr, 2023
The chomp() function in Perl is used to remove the last trailing newline from the input string.
Syntax: chomp(String) Parameters: String : Input String whose trailing newline is to be removed Returns: the total number of trailing newlines removed from all its arguments
Example 1:
Perl
#!/usr/bin/perl
$string = "GfG is a computer science portal\n";
$A = chomp ( $string );
print "Chopped String is : $string \n";
print "Number of Characters removed : $A ";
|
Output:
Chopped String is : GfG is a computer science portal
Number of Characters removed : 1
In the above code, it can be seen that input string containing a newline character (\n) which is removed by chomp() function. Example 2:
Perl
#!/usr/bin/perl
$string1 = "Geeks for Geeks\n\n";
$string2 = "Welcomes you all\n";
$A = chomp ( $string1 , $string2 );
print "Chopped String is : $string1 $string2 \n";
print "Number of Characters removed : $A \n";
|
Output:
Chopped String is : Geeks for Geeks
Welcomes you all
Number of Characters removed : 2
In the above code, it can be seen that the input string1 containing two newline characters (\n\n) out of which only last newline character is removed by chomp() function and second last newline character is utilized which can be seen in the output.
The chomp() function in Perl is used to remove the newline character (\n) from the end of a string.
Here’s an example code that uses the chomp() function to remove the newline character from a string:
Perl
#!/usr/bin/perl
my $string = "Hello, world!\n" ;
chomp $string ;
print "$string" ;
|
In this code, the chomp() function is used to remove the newline character from the end of the string “Hello, world!\n”. The resulting string “Hello, world!” is then printed to the console using the print() function.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...