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


In reply to Re: Re: How to flatten an x-dimensional array? by demerphq
in thread How to flatten an x-dimensional array? by Incognito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.