1. Perl
  2. builtin functions
  3. here

split function - split string

You can use the split function to split string by specifying a delimiter.

my @ret = split(/,/, $person_csv);

In the first argument, specify the delimiter with regular expression. In the second argument, specify the string you want to split. The return value is array of the split strings.

Use a regular expression

Since the split function receives a regular expression as the first argument, it is easy to split with multiple spaces.

my @ret = split(/ +/, $line);

Concatenation of strings

The split function splits a string. the opposite is the join function if you want to concatenate the strings with a delimiter. See the following article for the join function.


This is an example program of the split function.

CSV data

This is an example to convert CSV format data to an array.

# Convert CSV format data to array
my $string = 'a,b,c';
my @record = split /,/, $string;

Blank delimiter

This is an example to convert a string separated by blanks to an array.

# Convert data separated by blanks to an array
my $string = 'a b c';
my @record = split /\s+/, $string;

Comma separated

This is an example that processes comma-separated strings.

use strict;
use warnings;

# 1: Process comma separated strings.
my $header_csv = "name,age,country\n";
my $person_csv = "kaori,23,Japan\n";

# Remove a line break with chomp function
chomp $header_csv;
chomp $person_csv;

# Use the split function to specify a comma as the delimiter.
# split(/delimiter/, string)
my @header = split(/,/, $header_csv);
my @person_attribute = split(/,/, $person_csv);

print "1: Process comma separated strings.\n";
print "\$header_csv = $header_csv\n";
print "\$person_csv = $person_csv\n";
print "\n";

for my $i (0 .. 2) {
  print "\$header[$i] =" . $header[$i] . "\n";
  print "\$person_attribute[$i] =" . $person_attribute[$i] . "\n\n";


1: Process comma separated strings.
$header_csv = name,age,country
$person_csv = kaori,23,Japan

$header[0] =name
$person_attribute[0] =kaori

$header[1] =age
$person_attribute[1] =23

$header[2] =country
$person_attribute[2] =Japan

Related Informatrion