in reply to How to flatten an x-dimensional array?

Yes, this is certainly possible - The following simple example uses recursion to iterate through the data object.

my @array = ( [ '', '' ], [ '', '' ], [ 'funct1', '', '' ], [ '', '' ], [ '', [ '', [ 'funct2a', 'funct2b', '' ], '' ], '' ], 'funct3', 'funct4', 'funct5', 'funct6', 'funct7', ); print join "\n", _flatten( @array ), "\n"; { my @results; sub _flatten { foreach (@_) { if (ref $_ eq 'ARRAY') { _flatten( @{ $_ } ); next; } push @results, $_ if $_; } return @results; } }

If however, this code is to be used in a production environment, I would consider either rewriting the above to include depth checking and/or a shift towards a iterative rather than recursive loop, or alternatively, reevaluate the code generating this complex data structure in the first place.

 

perl -e 's&&rob@cowsnet.com.au&&&split/[@.]/&&s&.com.&_&&&print'

Replies are listed 'Best First'.
Re: Re: How to flatten an x-dimensional array?
by demerphq (Chancellor) on Mar 12, 2002 at 14:26 UTC
    Well, heres a version that responds to a couple of your concerns, and a couple of mine. For instance all of the posted solutions break if the array is blessed, I thought monks at our level weren't supposed to fall into the 'ref' trap ;-). Also I use a variant of 'Annony's solution, but without the grep as I wanted a general solution (note that his use of map AND grep is superfluous, the whole shebang can be done in one map).

    I use overload::StrVal to keep a record of seen nodes to avoid cycles. This means its not ncessary to keep a depth count. Also I cant see much benefit in writing this iteratively. You'd have to maintain your own stack and the overhead for this situation (imo) isn't worth the bother.

    use overload; use Carp; sub flatten { my $ref = shift; my $seen = shift || ""; return map { (UNIVERSAL::isa($_,"ARRAY")) ? do { my $ref_str=overload::StrVal($_); Carp::croak "Cant flatten cyclic data structure !" if index($seen,$ref_str)>=0; flatten($_,$seen."$ref_str"); } : $_ #change to #} : $_ ? $_ :()# to simulate grep } @$ref; } require Data::Dumper; print Data::Dumper::Dumper([ flatten([qw(array of elements), [qw(and arrays)], bless [qw(even blessed ones)],"FooArray" ]) ]); __END__ $VAR1 = [ 'array', 'of', 'elements', 'and', 'arrays', 'even', 'blessed', 'ones' ];

    Fixed spelling mistake.

    Yves / DeMerphq
    --
    When to use Prototypes?
    Advanced Sorting - GRT - Guttman Rosler Transform