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.
The split() function splits a string into smaller components on the basis of a user-specified pattern, and then returns these elements as an array.
#!/usr/bin/perl
$str = "I'm not as think as you stoned I am";
# split into individual words on whitespace delimiter and store in array
@words @words = split (/ /, $str);
This function is particularly handy if you need to take a string containing a list of items (for example, a comma-delimited list) and separate each element of the list for further processing. Here's an example:
#!/usr/bin/perl
$str = "Rachel,Monica,Phoebe,Joey,Chandler,Ross";
# split into individual words and store in array
@arr = split (/,/, $str);
# print each element of array
foreach $item (@arr)
{
print("$item\n");
}
Here's the output:
Rachel
Monica
Phoebe
Joey
Chandler
Ross
Obviously, you can also do the reverse - the join() function creates a single string from all the elements of an array, glueing them together with a user-defined separator. Reversing the example above, we have:
#!/usr/bin/perl
@arr = ("Rachel", "Monica", "Phoebe", "Joey", "Chandler", "Ross");
# create string from array
$str = join (" and ", @arr);
# returns "Rachel and Monica and Phoebe and Joey
# and Chandler and Ross are friends"
print "$str are friends";