Perl chop() and chomp()

Both the functions are quite similar. Both of them remove one character from the end of the given string.

Perl chop()

The Perl chop() function removes last character from a string regardless of what that character is. It returns the chopped character from the string.

Syntax:

snippet
chop();

Perl chop() example

snippet
#chop() EXAMPLES  
$a = "AEIOU";  
chop($a);  
print "$a\n";  #it will return AEIO.  
$a = "AEIOU";  
$b = chop($a);  
print "$b\n";  #it will return U.

Output:

Output
AEIO U

Look at the output, at first, variable $a is printed after chopping. Then variable $b is printed which returns the chopped character from the string.

Perl chomp()

The chomp() function removes any new line character from the end of the string. It returns number of characters removed from the string.

Syntax:

snippet
chomp();

Perl chomp() example

snippet
#chomp() EXAMPLES  
$a = "AEIOU";  
chomp($a);  
print "$a\n";  #it will return AEIOU. 
$a = "AEIOU";  
$b = chomp($a);  
 print "$b\n"; #it will return 0, number .
 $a = "AEIOU\n";  
chomp($a);  
print "$a\n";  #it will return AEIOU, removing new line character.  
$a = "AEIOU\n";  
$b = chomp($a);  
print "$b\n";  #it will return 1, number of characters removed.

Output:

Output
AEIOU 0 AEIOU 1

Look at the output, at first, variable $a does not contain any new lone character. Then it is passed in variable $b and printed. It returns 0 as no character is removed.

Now, variable $a contains a new line character. When it is passed in $b, it returns 1 as it removes one new line character.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents