Perl | chomp() Function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# Initialising a string
$string = "GfG is a computer science portal\n";
  
# Calling the chomp() function
$A  = chomp($string);
  
# Printing the chopped string and 
# removed trailing newline character
print "Chopped String is : $string\n";
print "Number of Characters removed : $A";

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# Initialising two strings
$string1 = "Geeks for Geeks\n\n";
$string2 = "Welcomes you all\n";
  
# Calling the chomp() function
$A  = chomp($string1, $string2);
  
# Printing the chopped string and 
# removed trailing newline character
print "Chopped String is : $string1$string2\n";
print "Number of Characters removed : $A\n";

chevron_right


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.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.