Mar 23, 2013

Chop Vs Chomp

Now, we discuss about Chop & Chomp functionality in Perl

Chop:
It removes the last character of the string completely (even if the last character is new line or a character)

Chomp:
It only removes the last character if it is a newline. 
Chomp is more useful when we are reading the files to trim the new line characters


Chop: It removes the last character of the string completely

E.g., chop_test.pl

#!/usr/bin/perl
use strict;
use warnings;

$name = "Mother Teresa";
print "Name before chop: " . $name;  
chop($name); 
print "Name after chop: " . $name;  

O/P:
Name before chop : Mother Teresa
Name after chop    : Mother Teres


Chomp: It only removes the last character if it is a newline. 

E.g., chomp_test.pl

#!/usr/bin/perl
use strict;
use warnings;

$name = "Mother Teresa\n";
print "Name before chomp: " . $name;  
chomp($name); 
print "Name after chomp: " . $name;  

O/P:
Name after chomp: Mother Teresa

Name after chomp: Mother Teresa

No comments:

Post a Comment