How to use the Perl join function with an AOA (array of arrays)

Perl join function is used to concatenate the elements of an array or a list into a string, using a separator given by a scalar variable value. For a simple array, I remind you the usual syntax form:

$string = join EXPR, LIST;

where:

EXPR may be any string and it represents a separator for the elements of the list or array

LIST represents a list or array whose elements will be merged into a string

If you have an array of arrays (@AOA), you can use some additional syntax forms for the join function.

I’ll illustrate this by giving you a few examples.

Join into a string the elements of a particular sub-array

To join into a string the elements of a sub-array, you can use the following syntax form:

$string = join EXPR, @ { $AOA [ $index ] };

where $index is the index or subscript of the given sub-array.

$AOA[$index] is a reference to a sub-array, so you need to dereference it by putting a @ sign in front of the reference; to avoid any ambiguity or operators precedence rule, the reference is enclosed by braces.

The [] is the array constructor and returns a reference to the list enclosed in the square brackets. To join the elements of the subarray, the comma character was used.

Join the elements of a particular column of a matrix into a string

If you have a matrix represented as an array of arrays, than you can extract the elements of a particular column and join them into a string, by using map and join:

$str = join EXPR, map $_->[$index], @AOA;

where $index is the index of the matrix column.

@AOA contains array references, the map function will extract for each reference assigned to $_ the corresponding element of the $index column; for dereferencing the -> operator was used because is more easier to read (if you prefer you can use also the notation $$_[$index]). The join function will join the elements of the list returned by map into a string, separating them by EXPR.

As you can see from the output, the $str variable contains the elements of the matrix second column, separated by comma.

Turn each subarray into a string and get an array with all these strings

If you have an array of arrays, you can use foreach to iterate through its array references and for each sub-array you can join its elements into a string using an EXPR separator and next append this string into an array using the push function.

You can use either an explicit foreach loop with a block or the short form of foreach as a modifier.