Subject: | Flatten arrays to any level |
Code attached.
Subject: | flatten.pl |
use strict ;
use warnings ;
use Benchmark qw(:all) ;
my $data =
[
[
[0],
1,
[
[2, 3],
],
],
4,
[
[5],
6,
[
[7, 8],
],
],
9,
] ;
sub flatten
{
map
{
(ref($_) eq 'ARRAY')
? flatten(@$_ )
: $_
} @_
}
sub flatten_non_recursive
{
my @flattened ;
my @left = shift ;
while(@left)
{
while(@left && 'ARRAY' ne ref $left[0])
{
push @flattened , shift(@left) ;
}
while('ARRAY' eq ref $left[0])
{
unshift @left, @{shift(@left)} ;
}
}
return @flattened ;
}
print flatten $data ; print "\n" ;
print flatten_non_recursive $data ; print "\n" ;
cmpthese(10_000, {
'flatten' => sub {flatten $data},
'flatten_non_recursive' => sub {flatten_non_recursive $data},
});