How to join array elements into a string in Perl?
Question
How to join array elements into a string in Perl?
Joining Array Elements into a String in Perl
In Perl, the common way to combine or concatenate array elements into a single string is by using the built-in join function. This function takes two main arguments: a delimiter string and an array (or list) of elements. It returns a single string made by concatenating all array elements with the delimiter placed between each pair.
This is especially useful when you want to output array contents as a CSV line, a space-separated sentence, or simply to merge data into one string.
Basic Syntax
join $delimiter, @array
$delimiter: String to insert between elements (like a comma,, space, or empty string).@array: List or array of values to join.
Example: Joining Array Elements with Comma
use strict;
use warnings;
# Define an array of fruits
my @fruits = ('apple', 'banana', 'cherry');
# Join elements with a comma and space delimiter
my $joined = join(", ", @fruits);
print "Joined string: $joined\n";
Output:
Joined string: apple, banana, cherry
Explanation of Perl-Specific Concepts
- Sigils: The
@beforefruitsindicates we are dealing with an array. When passed tojoin, it is treated as a list of scalar values. - Context:
joinexpects a list, so arrays provide a list context here. - TMTOWTDI: Perl offers multiple ways to concatenate arrays and strings. While
joinis the idiomatic approach, you can also manually concatenate elements using loops or map, butjoinis simpler and more efficient.
Additional Examples
# Join without any delimiter (empty string)
my $no_delim = join("", @fruits);
print "No delimiter: $no_delim\n"; # applebananacherry
# Join with newline character
my $newlines = join("\n", @fruits);
print "With newlines:\n$newlines\n";
Common Pitfalls
- Forgetting that
joinrequires a delimiter string, even an empty string''. Omitting it leads to a syntax error. - Passing a scalar with array sigil (
@) accidentally rather than the array name.
Correct:join(", ", @array)
Incorrect:join(", ", $array)(here$arraywould be a scalar, not a list) - Be mindful that elements are joined in list context; if the array contains array references or other complex structures, you may need to dereference or stringify properly.
Version Notes
joinis core Perl functionality available since very early versions and is fully supported in all Perl 5 releases.
In summary, join is the standard, clean, and efficient way to combine array elements into a single string in Perl. It leverages Perl’s easy TMTOWTDI philosophy for flexible string handling.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 4ms
(empty)(empty)