split and join
split breaks a string into pieces and join glues pieces back into a string.
In this page:
split and join
split takes a pattern, a string and an optional limit and returns a list of the pieces between the separators. join takes a separator and a list and returns one string. A pattern of a single space, written ' ', is special: it splits on any run of whitespace and ignores leading whitespace.
Note:
split removes trailing empty fields unless you pass a negative limit such as -1.
Example: split and join
use strict;
use warnings;
my @fields = split /,/, "red,green,blue";
print "fields: ", scalar(@fields), " -> @fields\n";
my @words = split ' ', " many spaces here ";
print "words: ", join("|", @words), "\n";
my @limited = split /:/, "a:b:c:d", 2;
print "limited: ", join(" / ", @limited), "\n";
my @trailing = split /,/, "a,b,,,";
print "trailing dropped: ", scalar(@trailing), "\n";
my @kept = split /,/, "a,b,,,", -1;
print "trailing kept: ", scalar(@kept), "\n";
my @chars = split //, "perl";
print "chars: @chars\n";
print "joined: ", join("-", @chars), "\n";
my @dots = split /\./, "192.168.1.10";
print "octets: @dots\n";
# Output:
# fields: 3 -> red green blue
# words: many|spaces|here
# limited: a / b:c:d
# trailing dropped: 2
# trailing kept: 5
# chars: p e r l
# joined: p-e-r-l
# octets: 192 168 1 10
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Passing a plain string with regex special characters like "." or "+" to split
- Forgetting that trailing empty fields are removed
- Using join with the list first instead of the separator first
Chapter Summary
- split pattern, string, limit
- join separator, list
- split ' ' splits on runs of whitespace
- Trailing empty fields are removed by default
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: