perl - better way for converting multidimensional array to one dimensional array -


currently, using following code convert irregular multidimensional array 1 dimensional array.

my $array = [0,          [1],         2,         [3, 4, 5],         [6,              [7, 8, 9 ],         ],         [10],         11,         ];  @mylist; getlist($array);  print dumper (\@mylist);   sub getlist  {          $array = shift;          return if (!defined $array);         if (ref $array eq "array")         {                foreach $i (@$array)                {                    getlist($i);                }         }         else         {                print "pushing $array\n";                push (@mylist, $array);         } } 

this based on recursion checking each element. if element reference array calling recursively new array.

is there better way solve kind of problem?

first of function should never return data modifying global variable. return list instead.

as efficiency, perl has surprisingly large function call overhead. therefore large data structures prefer non-recursive approach. so:

use data::dumper; $array = [   0,    [1],   2,   [3, 4, 5],   [6, [7, 8, 9 ]],   [10],   11, ];  @mylist = get_list($array);  print dumper (\@mylist);  sub get_list {     @work = @_;     @result;     while (@work) {         $next = shift @work;         if (ref($next) eq 'array') {             unshift @work, @$next;         }         else {             push @result, $next;         }     }     return @result; } 

note formatting using here matches recommendations of perlstyle. know futility of arguing 1 true brace style. @ least i'm going suggest reduce 8 space indent. there research this, , code comprehension has been shown improved indents in 2-4 space range. read code complete details. doesn't matter in range young people, older programmers eyesight going find 4 better indent. read perl best practices more on that.


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -