Regular Expressions   «Prev  Next»
Lesson 11 Perl split function
ObjectiveGiven a set of text data, write a Perl program that uses the split function to get just the browser name and version.

Perl Split Function

The split function is, in some ways, the inverse of the join function. However, it is more powerful than that description may imply, because it uses a regular expression to specify where the splits occur.
The split function returns a list comprising all the resulting elements from splitting a string.
Any of these forms are acceptable for invoking split:
  1. split /PATTERN/, EXPR, LIMIT
  2. split /PATTERN/, EXPR
  3. split /PATTERN/
  4. split

The /PATTERN/ parameter dictates where the string is split.
The EXPR parameter is the string from which the split is derived.
The LIMIT parameter is a number specifying the maximum pieces to split from the string (however, the split may result in fewer pieces).
If LIMIT is omitted, the results will be as many pieces as may be made using the pattern to split the string; if EXPR is omitted, the special $_ string is used for the input string; and if /PATTERN/ is omitted, the string is split on whitespace, after omitting any leading whitespace.
Here are several examples that illustrate the power of the split function.
The fact that the split function uses a regex to split strings makes it far more powerful than if it just split based on a simple mask. There are many circumstances in which you will probably choose to use the pattern match (m//) operator instead, but this little function is not to be underestimated.

Perl Split Function - Exercise

Click the Exercise link below to use the split function with a specified set of data.
Perl Split Function - Exercise