Softpanorama
(slightly skeptical) Open Source Software Educational Society

May the source be with you, but remember the KISS principle ;-)

Softpanorama Search

Introduction to Perl for Unix System Administrators

(Perl without excessive complexity)

by Dr Nikolai Bezroukov


Prev | Up | Contents | Down | Next

5.5. Split() Function

Split function is one the few Perl function that have regular expression as an argument. Its purpose is to take a string and convert it to an array or list breaking at points where the fitst argument (delimiter) specified with the regular expression matches. 

The usual syntax for the split function is

list = split (pattern, string_value);

Here, string_value is the string to be split. pattern  is a regular expression to be searched for. Again, it is important to understand that a new element is started every time pattern is matched; pattern  itself is not included as part of any element serving as a separator between elements.).  The resulting list of elements is returned in list.

For example, the following statement breaks the character string stored in $line into elements delimited by ":", and store them into the array @tokens:

@tokens = split (/:/, $line);

You can specify the maximum number of elements of the list produced by split by specifying the maximum as the third argument. For example:

$line = "This:is:a:string";

@tokens = split (/:/, $line, 3);

As before, this breaks the string stored in $line into elements. After two first elements have been created, no more new elements are created. The rest of the string is assigned to the third element of arrayt. A In this case, the list assigned to @list is ("This", "is", "a:string").

You can also assign to several scalar variables at once:

$line = "11 12 13 14 15";
($var1, $var2, $line) = split (/\s+/, $line, 3);
This splits $line into the list ("11", "12", "13 14 15"). $var1 is assigned 11, $var2 is assigned 12, and $line is assigned "13 14 15". This enables you to assign the "leftovers" to a single variable, which can then be split again at a later time

Additional examples

$_ = 'AB AB AC';
print m/c$/i

Prev | Up | Contents | Down | Next



Copyright © 1996-2009 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. Submit comments This document is an industrial compilation designed and created exclusively for educational use and is placed under the copyright of the Open Content License(OPL). Site uses AdSense so you need to be aware of Google privacy policy. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

Disclaimer:

Last modified: September 05, 2009