← Back to Perl Course | Chapter 3: Strings | Lesson 6 of 7

split and join

split breaks a string into pieces and join glues pieces back into a string.

In this page:

  1. split and join

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

perl
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
Common Mistakes
  1. Passing a plain string with regex special characters like "." or "+" to split
  2. Forgetting that trailing empty fields are removed
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.