1. Perl
  2. builtin functions
  3. here

join function - join array with delimiter

You can use the join function to join arrays by specifying a delimiter.

my $joined = join(',', @array);

The first argument is the delimiter. In this example, a comma is specified as the delimiter. The strings contained in the array given in the second and subsequent arguments are combined with a delimiter.

See the following simple example. Here is a simple example of how to use the join function. CSV data is created by concatenating the strings contained in the array with commas.

# Create "Yuki, Toro, Kato" from an array
my @names = ('Yuki', 'Taro', 'Kato');
my $names_csv = join(',', @names);

The delimiter can be anything, and the tab character "\t" is often used.

# Create "Yuki Toro Kato" from the array
my @names = ('Yuki', 'Taro', 'Kato');
my $names_csv = join("\t", @names);

Strings rarely contain tabs, so they are often easier to work with than commas.

If you add a line break at the end, you can easily create one line of data separated by tabs.

my $line = join("\t", @names) . "\n";

Decompose to array by specifying delimiter

You can use split function to split into an array by doing the opposite of the join function, that is, by specifying a delimiter.

my @names = split(/,/, "Yuki, Taro, Kato");

Push function to add data to the array to join

If you want to add data to combine, you can use push function.

push @names, 'Kenta';

Example join function

This is an example that joins characters by "tab" using the join function.

use strict;
use warnings;

# Concatenate multiple strings with tabs
my @animals = qw(cat dog sheep);
my $line = join("\t", @animals);

Reference: qw() String concatenation operator

Related Informatrion