Created
December 9, 2016 07:13
-
-
Save Dodotree/2c7e6ebe3de3e060a8240560b66cacc2 to your computer and use it in GitHub Desktop.
flatten
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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