Perl String Processing
(Page 1 of 2 )
If you're learning how to use Perl, you may already be aware of its power as a text processing language. It gets that power in a number of ways, not the least of which is its built-in string operators and string functions. This three-part article series will show you some of the many ways in which you can process strings in Perl. It is excerpted from chapter nine of the book Beginning Perl, Second Edition, written by James Lee (Apress; ISBN: 159059391X).
Perl was created to be a text processing language, and it is arguably the most powerful text processing language around. One way that Perl displays its power in processing text is through its built-in regular expression support that we discussed in Chapter 7. Perl also has many built-in string operators (such as the string concatenation operator.and the string replication operatorx) and string functions. In this chapter we will explore several string functions and one very helpful string operator.
Before we get started with some of Perl’s built-in functions, we should talk about the ability to access characters in a string by indexing into the string. The numeric position of a character in a string is known as its index. Recall that Perl is 0-based—it starts counting things from 0, and this applies to character indexing as will. So, for this string:
"Wish You Were Here"
here are the characters of the string and their indexes:
character 0: W
We can also index characters by starting at the right-most character and counting down starting from –1 (much like accessing an array). Therefore, the characters in the preceding string are also known by these indices:
character -1: e
Perl has many string functions built into the language. We will now discuss several of the most common functions used to process text.
The length() Function
To determine the length of a string, we can use the length()function.
This function returns the number of characters of its argument. If no argument is given,length()returns the number of characters of$_. Here is an example:
my $song = 'The Great Gig in the Sky';
$_ = 'Us and Them';
Running this code produces the following:
$ perl length.pl