What\'s the easiest way to flatten a multidimensional array ?
The easiest and most natural way, is to iterate over the values and use the @ operator to "dereference" / "unpack" any existing nested values to get the constituent parts. Then repeat the process for every reference value encountered.
This is similar to Viajayenders solution, but works for values not already in an array reference and for any level of nesting:
sub flatten {
map { ref $_ ? flatten(@{$_}) : $_ } @_;
}
Try testing it like so:
my @l1 = [ 1, [ 2, 3 ], [[[4]]], 5, [6], [[7]], [[8,9]] ];
my @l2 = [ [1,2,3,4,5], [6,7,8,9] ];
my @l3 = (1, 2, [3, 4, 5], 6, [7, 8], 9); # Example from List::Flatten
my @r1 = flatten(@l1);
my @r2 = flatten(@l1);
my @r3 = flatten(@l3);
if (@r1 ~~ @r2 && @r2 ~~ @r3) { say "All list values equal"; }