String Processing with Perl - Making New Friends (
Page 4 of 8 )
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";