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.
$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:
$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)
Here's the output:
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:
@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";