split and join
split breaks a string into a list of pieces, and join glues a list back into a string. Together they are the bread and butter of processing delimited text such as CSV lines, paths and log records.
split /PATTERN/, STRING
The first argument is a regex describing the separator:
use strict;
use warnings;
my $csv_line = "Paris,France,2148000";
my ($city, $country, $population) = split /,/, $csv_line;
print "$city is in $country (population $population)\n";
my @parts = split /\s*;\s*/, "red ; green;blue ; yellow";
print join("|", @parts), "\n";
my @words = split ' ', " leading and multiple spaces ";
print scalar(@words), " words: @words\n";Paris is in France (population 2148000)
red|green|blue|yellow
4 words: leading and multiple spaces
The special separator ' ' (a single-space string) splits on any run of whitespace and ignores leading whitespace, like awk. It is the best way to split text into words. A regex / / would instead split on every single space and produce empty fields.
Splitting into characters and limiting fields
An empty pattern splits between every character. A third argument limits the number of fields, keeping the rest of the string intact in the last one:
use strict;
use warnings;
my @letters = split //, "perl";
print "Letters: @letters\n";
my $header = "Subject: Meeting: Monday at 10:00";
my ($key, $value) = split /:\s*/, $header, 2;
print "Key: $key\nValue: $value\n";
my @all = split /:\s*/, $header;
print "Without limit: ", scalar(@all), " fields\n";Letters: p e r l
Key: Subject
Value: Meeting: Monday at 10:00
Without limit: 4 fields
Empty fields
split keeps empty fields in the middle, but drops trailing empty fields. Pass a negative limit to keep them:
use strict;
use warnings;
my $record = "id,name,,email,,";
my @default = split /,/, $record;
my @keep = split /,/, $record, -1;
print "Default: ", scalar(@default), " fields: ", join("|", @default), "\n";
print "Keep all: ", scalar(@keep), " fields: ", join("|", @keep), "\n";Default: 4 fields: id|name||email
Keep all: 6 fields: id|name||email||
This matters for data where the number of columns must be fixed.
Note: Real CSV can contain quoted fields with commas inside (
"Smith, John",42). Plainsplit /,/cannot handle that; the CPAN module Text::CSV does. For simple, comma-free data,splitis fine.
Capturing separators
If the pattern has capture groups, the captured separators are included in the result. That is useful for tokenizing:
use strict;
use warnings;
my @tokens = split /([+\-*\/])/, "12+7*3-4";
print join(" ", @tokens), "\n";12 + 7 * 3 - 4
join
join EXPR, LIST puts the string EXPR between the list elements (not at the ends):
use strict;
use warnings;
my @dirs = ("home", "maya", "projects");
print "/", join("/", @dirs), "\n";
my %env = (LANG => "en_US", HOME => "/home/maya");
print join("; ", map { "$_=$env{$_}" } sort keys %env), "\n";
print join(", ", 1 .. 5), "\n";
print "[", join("", ("ab") x 3), "]\n";/home/maya/projects
HOME=/home/maya; LANG=en_US
1, 2, 3, 4, 5
[ababab]
A small pipeline
split, map, grep and join combine into compact data transformations. Here we parse key=value pairs, clean them and rebuild a sorted query string:
use strict;
use warnings;
my $query = "q=perl+books& page=2 &sort=&lang=EN";
my %params = map { split /=/, $_, 2 }
grep { /=./ } # drop empty values
map { s/^\s+|\s+$//gr } # trim spaces
split /&/, $query;
print join("&", map { "$_=" . lc $params{$_} } sort keys %params), "\n";lang=en&page=2&q=perl+books
Test yourself
What does split ' ', " a b " return?
('', 'a', 'b')('a', 'b')(' ', 'a', ' ', 'b')(' a b ')
How many elements does split /,/, "a,b,," produce?
- 2
- 3
- 4
- 1
What does join('-', 'x', 'y', 'z') return?
-x-y-z-x-y-zxyz-x y z