天天看点

chop() vs. chomp() of Perl

  Chomp is a "built-in" Perl command. It has a rather odd job. It takes off the end character of a specified string ONLY if that character is a RETURN (Enter). The return character is sometimes created from input information or by the coding itself. Either way, to parse that character off, CHOMP is the command to use. It will not affect any other characters.

Note : The RETURN character is the same as the ENTER character which is also known as a NEWLINE character. It is symbolized as \n.

Quick example...

#!/usr/bin/perl

# set the value with a return character.

$input = "Test\n";

# print the current value.

print "$input <br>";

# chomp the data and print the value once, twice, three times.

chomp ($input);

print "After one chomp the value is now $input <br>";

chomp ($input);

print "After two chomps the value is now $input <br>";

chomp ($input);

print "After three chomps the value is now $input";

The result: Test

 <br>After one chomp the value is now Test <br>After two chomps the value is now Test <br>After three chomps the value is now Test

Ok, so that isn't really the best example, but hey, it's hard to figure a way to show an invisible thing dissappear. What it does show though is that chomp did not take away any other ending characters.

The next command is CHOP. This is a very similar command as CHOMP, but... it takes of the ending character of a string no matter what it is.

Another quick example...

#!/usr/bin/perl

# set the value for the test.

$input = "Test\n";

# print the current value.

print "$input <br>";

# chop the data and print the value once, twice, three times.

chop ($input);

print "After one chop the value is now $input <br>";

chop ($input);

print "After two chops the value is now $input <br>";

chop ($input);

print "After three chops the value is now $input";

The result: Test

 <br>After one chop the value is now Test <br>After two chops the value is now Tes <br>After three chops the value is now Te

Note : The CHOP example shows the characters start subtracting off the end of the string, not starting with the ending return character.