What is chomp() function in Perl and why it is required

Following article explains what is chomp() function in Perl and why it is required? Chomp is a very important function in Perl. It is a safer version of chop function. Chomp function removes any new line characters from end of the String. In other terms we can say that it removes trailing string that corresponds to the current value of $/ i.e. $INPUT_RECORD_SEPARATOR . Chomp function also returns how many characters are removed.

chomp() function is one of the favorite topics of the interviewer. You will get questions like what is chomp function in Perl and where we use it? Now lets see how we can use chomp function with some examples.

Chomping a simple String



In the example below we are passing the String to the chomp function which is removing the \n characters from the String and printing the String without the \n character.

Perl Example of chomping a simple String





$strTest = "test\n";

chomp( $strTest );

print $strTest;

print "append";


Chomping a String as input from standard input stream (STDIN)



Whenever we get the input from user or reading from a file most of the times we use the chomp() function. In case of reading user input from standard input stream with each line we get the newline character. This new lien character is removed using chomp() method as shown in example below :

Perl Example of chomping a String as input from STDIN





use strict;

use warnings;

while (my $textInput = ) {

my $retval= chomp( $textInput );

print "You have entered '$textInput'\n";

print " Number of characters removed '$retval'\n";

last if ( $textInput eq '' );

}

Output :
a

You have entered 'a'

Number of characters removed '1'

test

You have entered 'test'

Number of characters removed '1'

You have entered ''

Number of characters removed '1'

Similar to chomping a String we can also do chomp on array and hash as shown below : chomp( @myArray ) and chomp( %myHash ) , similar to String all new line characters traling in String are removed from array and hash.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment