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

Note that your iterative solution can be slow with a long output list on any current Perl because iteratively building an array with unshift scales quadratically. (Fixed in the current development cycle.)

Given the pattern of unshift's and shift's in your code, you might or might not hit this problem. But still for a single reverse you can use the guaranteed efficient pop/push pair instead of shift/unshift:

sub flatten { my @flattened; # Will be in reverse order while (@_) { my $last = pop; if (UNIVERSAL::isa($last, "ARRAY")) { push @_, @$last; } else { push @flattened, $last; } } return reverse @flattened; }

Replies are listed 'Best First'.
•Re: Re (tilly) 2: How to flatten an x-dimensional array?
by merlyn (Sage) on Mar 12, 2002 at 20:23 UTC
    I think you missed a reverse there:
    push @_, @$last;
    needs to be
    push @_, reverse @$last;
    since you are reversing the result. Trivial example: $last = [1,2,3,4,5] must flatten as 5, 4, 3, 2, 1 so it can be reversed in the final result to 1, 2, 3, 4, 5 again.

    -- Randal L. Schwartz, Perl hacker

      Try running it. :-)