The split function is very useful for parsing or “splitting” a string into a list of strings based on a regular expression (delimiter). For example you could have a string like this:
“apple, orange, pear”
To parse this list with the split function you would do this:
print split /,/ , “apple, orange, pear”;
This will print a list with 3 elements. If you assign the result of the split function to a scalar you will simply get the number of elements or the count of items in the list. Usually you assign the result of the split function to an array:
@mylist = split /,/, “apple, orange, pear”;
Once you do this you could then assign it to a scalar like this:
$fruit = $mylist[0];
This would assign the value of apple to the $fruit scalar. However, I find that I use the split function to parse one value from a string. For example the url from a web page document:
<a href=”http://mysite.campfirenow.com/”>redirected</a>
In this case I want to parse out the http://mysite.camfirenow.com value using the split function and assign it to a scalar all in one line of code. To accomplish this you can write the code like this:
$address = (split /”/, “<a href=”http://mysite.campfirenow.com/”>redirected</a>”)[1];
In this example it is important to use the second element of the list. The first element ([0]) is undefined or empty. The second element ([1]) contains the url value.
Troy