1. Home
  2. Computing & Technology
  3. Perl

Perl array split() function - Quick Tutorial

How to use the split() function

By Kirk Brown, About.com

@LIST = split(/PATTERN/, STRING, LIMIT);
Perl's split() function is used to break a string into an array on a specific pattern. The PATTERN is a regular expression that can be as simple as a single character. By default the STRING is split on every instance of the PATTERN, but you can LIMIT it to a specific number of instances.
$myNames = "Jacob,Michael,Joshua,Matthew,Ethan,Andrew";
@nameList = split(/,/, $myNames);
In the above example, the split function takes a plain string of names, separated by commas. It then breaks the string apart on each instance of the comma, putting the results into the array @nameList. The value of @nameList would then be:
@myNames = ('Jacob', 'Michael', 'Joshua', 'Matthew', 'Ethan', 'Andrew');
By using the LIMIT option, you can split the array into a specific size. For example:
$myNames = "Jacob,Michael,Joshua,Matthew,Ethan,Andrew";
@nameList = split(/,/, $myNames, 3);
This would split the array into 3 chunks, so the value of @nameList would then be:
@myNames = ('Jacob', 'Michael', 'Joshua,Matthew,Ethan,Andrew');
More Perl Quick Tips

Explore Perl

More from About.com

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. Perl split function reference - learn how to use Perl's split() function in this quick tutorial.

©2008 About.com, a part of The New York Times Company.

All rights reserved.