Perl has always been known for its text processing and manipulation abilities. This article examines the Perl string handling API in greater detail, explaining how you can use Perl's string functions to (among other things) print and format strings, split and join string values, alter string case, and perform regular expression searches.
With the basics out of the way, let's now turn to some of the other string functions available in Perl. Other than print(), the two functions you're likely to encounter most often are chop() and chomp().
There's a very subtle difference between these two functions. Take a look at this next example, which demonstrates chop() in action.
$statement = "Look Ma, no hands";
The chop() function removes the last character from a string and returns the mutilated value - as the output of the above program demonstrates:
Look Ma, no hand
Now, how about chomp()?
# ask a question...
print "Gimme a number! ";
# get an answer...
# process the answer...
$square = $number * $number;
# display the result
print "The square of $number is $square\n";
In this script, prior to using the chomp() function, the variable $number contains the data entered by the user at the prompt, together with a newline (\n) character caused by pressing the Enter key. Before the number can be processed, it is important to remove the newline character, as leaving it in could adversely affect the rest of the program. Hence, chomp().
The chomp() function's sole purpose is to remove the newline character from the end of a variable, if it exists. Once that's taken care of, the number is multiplied by itself, and the result is displayed.
Gimme a number! 5
The square of 5 is 25
The length() function returns the length of a particular string, and can come in handy for operations which involve processing every character in a string.
$str = "The wild blue fox jumped over the ripe yellow pumpkin";
# returns 53