XML technologies / Regular expressions / Perl / The split operator

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

The versatile split function (operators in Perl are often loosely called functions ) is usually the counterpart to m/.../g in list context (see Extracting all matches: list context with /g). That returns the text matched by the regex; using split with the same regex returns the pieces in between. Searching with $Text =~ m/:/g in the subject ›IO.SYS:225558:95-10-03:-a-sh:optional‹ produces an uninteresting four-element list:

(':', ':', ':', ':')

An invocation of split(/:/, $Text) instead produces this five-element list:

('IO.SYS', '225558', '95-10-03', '-a-sh', 'optional')

Both examples show that the regex ˹:˼ matched four times. With split , a copy of the subject is cut at these four points, returning five substrings.

Here the delimiter is one character, but any regex can be used. For example,

@Paragraphen = split(m/\s*<p>\s*/i, $html);

splits HTML at each <p> or <P>, including the surrounding whitespace.

You can also invoke split at positions. This splits logical lines into actual lines:

 

@Zeilen = split(m/^/m, $zeilen);

In its simplest form, with simple data, split is easy and useful. Many options, special cases, and situations complicate it. Before discussing those, here are two particularly simple cases:

These special cases are explained later; the next sections cover simpler matters.

 

split basics

The split operator accepts up to three operands and looks like a function:

split(Match-Operand, Suchtext, Limit)

Parentheses are optional. All operands have defaults.

split is always used in list context, usually as in these examples:

($var1, $var2, $var3, ... ) = split(...);

@array = split(...);

for my $item (split(...)) {
   .
   . 
   .
}

 

Simple forms of the match operand

Special cases aside, this is generally the same regex operand as with the match operator. You can use /.../ or m{...} and similar forms, regex objects, or any string expression. Only the five general modifiers are allowed (see Regex modifiers).

For grouping, use noncapturing parentheses ˹(?:...)˼. Capturing parentheses activate a special case discussed in the next pages.

 

The subject operand

The subject is searched by split but never changed. With no subject specified, the default $_ is used.

 

Simple forms of the limit operand

Primarily, the third operand limits the number of pieces returned. With our sample data, split(/:/, $Text, 3) returns:

('IO.SYS', '225558', '95-10-03:-a-sh:optional')

This shows that split stops after two matches of /:/ and returns three elements. Further possible matches are irrelevant because of the limit. It is only an upper limit: fewer pieces are not padded with empty strings. split(/:/, $Text, 99) thus produces only five pieces. Still, split(/:/, $Text) and split(/:/, $Text, 99) differ in a way that does not appear here and is discussed later.

The limit counts pieces. With three matches, the preceding example would produce

('IO.SYS', '225558', '95-10-03', '-a-sh:optional')

; that is exactly what does not happen.

For efficiency, suppose you need only the first three fields:

($dateiname, $groesse, $datum) = split(/:/, $text)

Perl stops automatically after three fields, setting a limit one greater than the number requested.

 

Complex splitting

Using split is usually straightforward, but three practical complications arise:

  • split can return empty elements

  • Special regex operand forms in split

  • Capturing parentheses in the regex operand

The following sections explain these cases.

 

split can return empty elements

Normally, split returns text between matches. Consecutive matches yield the nothing between them as an empty string "". With

@nums = split(m/:/, "12:34::78");

, we get:

("12", "34", "", "78")

The regex ˹:˼ matches three times, returning four elements. The third, empty element simply means two consecutive matches with nothing between.

 

Trailing empty elements

Normally, trailing empty elements are not returned. With

@nums = split(m/:/, "12:34::78:::");

, we get the same four elements

("12", "34", "", "78")

as before, despite three further matches at the end. Normally, split removes trailing empty elements unless the limit operand has a particular value…

 

Another role for the limit operand

An explicit nonzero limit disables this removal. (Zero makes split behave as if the third operand were absent.) To preserve all elements without limiting their number, use a large or, better, negative number: negative means very, very large. Thus, split(/:/, $Text, -1) returns everything, including trailing empty elements.

At the other extreme, if you want no empty elements, even internal ones, insert before split the construct grep {length}. The grep passes only nonempty elements, those whose length exceeds zero:

my @NichtLeere = grep { length } split(/:/, $text);

 

Special behavior at the string's beginning

A match at the beginning normally produces an empty element:

@nums = split(m/:/, ":12:34::78");

The array @nums receives:

("", "12", "34", "", "78")

The initial empty element indicates a match at the start. But a match at the start or end that consumes no text (matching a position ) causes those empty elements not to be returned. With split(/\b/, "Ein kleiner Test"), the regex matches at six marked positions in ›▵Ein▵●▵kleiner▵●▵Test▵‹. Despite six matches, only five elements, not seven, are returned: ("Ein", " ", "kleiner", " ", "Test"). We already encountered this special case with @Zeilen = split(m/^/m, $zeilen).

  

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top