Skip to content

Instantly share code, notes, and snippets.

@Dodotree
Created December 9, 2016 07:13
Show Gist options
  • Select an option

  • Save Dodotree/2c7e6ebe3de3e060a8240560b66cacc2 to your computer and use it in GitHub Desktop.

Select an option

Save Dodotree/2c7e6ebe3de3e060a8240560b66cacc2 to your computer and use it in GitHub Desktop.
flatten
#!/usr/bin/perl
use strict;
use Data::Dumper;
my @tst = ( [1,2], 3, [4, [5,6], 7] );
print Dumper(\@tst);
my @flat = @{flatten(\@tst)};
print Dumper(\@flat);
sub flatten{
my $arr = shift;
my @ret = ();
foreach my $e (@{$arr}){
if (ref(\$e) eq "SCALAR"){
push @ret, $e;
} else {
my @tail = @{flatten( $e )};
push @ret, @tail;
}
}
return \@ret;
}
__END__
root@n1:~# ./tt.pl
$VAR1 = [
[
1,
2
],
3,
[
4,
[
5,
6
],
7
]
];
$VAR1 = [
1,
2,
3,
4,
5,
6,
7
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment