How to split a string into an array in Perl?

Question

How to split a string into an array in Perl?

Splitting a string into an array is a fundamental task in Perl. The primary function to accomplish this is split. It divides a string into a list of substrings based on a specified pattern, usually a delimiter such as a space or comma. This list can then be stored in an array.

Understanding split in Perl

The split function takes a pattern (usually a regular expression) and a string, and returns a list of substrings separated by where the pattern matches. This list is often assigned to an array.

Basic syntax:

my @array = split /PATTERN/, $string;
  • The pattern can be a regex, e.g., /\s+/ for whitespace
  • If PATTERN is a single space ' ', it splits on whitespace and treats multiple spaces as one
  • If the PATTERN is omitted but $_ is set, split works on $_ by default

Example: Split a comma-separated string into an array

#!/usr/bin/perl
use strict;
use warnings;

my $string = "apple,banana,orange,grapefruit";

# Split on comma characters
my @fruits = split /,/, $string;

print "Fruits:\n";
foreach my $fruit (@fruits) {
    print "> $fruit\n";
}

This script will output:

Fruits:
> apple
> banana
> orange
> grapefruit

More notes on split and common pitfalls

  • Splitting on whitespace: If you want to split words separated by any amount of whitespace, use split ' ', $string;. This treats multiple spaces as a single delimiter, unlike split /\s+/ which behaves similarly.
  • Using capture groups: Capturing parentheses in the pattern cause the matched delimiters themselves to be included in the output array. This can be helpful if you want to keep delimiters, but is often not intended.
  • Limit parameter: split optionally accepts a third argument that limits the number of fields returned. Useful to avoid splitting an entire string unexpectedly in cases like CSV parsing.
  • Context matters: split returns a list in list context, so assigning to an array is most common. In scalar context, it returns the number of fields produced.

Summary

In Perl, split is the go-to function for splitting strings. Using patterns such as /,/ for commas or ' ' for whitespace, you can easily break a string into parts. Make sure to assign the result to an array to collect all parts, and remember the subtle differences in how patterns behave.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 6ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions