in reply to Re: How to flatten an x-dimensional array?
in thread How to flatten an x-dimensional array?

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