zerocred has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have totally confused myself with arrays. I have an anon 2d array (arbitrary size) that looks like this:
$a = [[1,2,3],[4,5,6]...]
and I want it to transform it to look like this:
$b = [[1,2],[3],[4,5],[6]...]

Ok in formulating my question I think I solved it:
foreach $row (0..$#A){ #array row length foreach $col (0 .. ($#{$A[0]} - 1) ) { #array width less one $b->[$row*2][$col] = $a->[$row][$col]; # copy all but last ele ove +r } $b->[($row *2) +1][0] = $a->[$row][$#{$A[0]}]; #now copy last #there are twice as many rows so we double the row index }
Solved - but is there a neater way? Array slices? z

Replies are listed 'Best First'.
Re: array confusion
by jwkrahn (Abbot) on May 11, 2012 at 05:55 UTC
    $ perl -e' use Data::Dumper; my $A = [[1,2,3],[4,5,6]]; print Dumper $A; @$A = map { [ splice @$_, 0, 2 ], $_ } @$A; print Dumper $A; ' $VAR1 = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]; $VAR1 = [ [ 1, 2 ], [ 3 ], [ 4, 5 ], [ 6 ] ];

      Personally I find pop a little more readable.

      use Data::Dumper; my $A = [[1,2,3],[4,5,6]]; @$A = map { $_, [pop @$_] } @$A; print Dumper($A);
      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
      Now that... is just ingenious. And extremely quick! Thanks!!
Re: array confusion
by BrowserUk (Patriarch) on May 11, 2012 at 06:04 UTC
    Solved - but is there a neater way?

    Neater is in the eye of the beholder:

    $a = [[1,2,3],[4,5,6],[1],[1..4],[1..5]];; $b = [ map{ my @x; push @x, [ shift(@$_),shift(@$_)//() ] while @$_; @ +x } @$a ];; pp $b;; [[1, 2], [3], [4, 5], [6], [1], [1, 2], [3, 4], [1, 2], [3, 4], [5]]

    Oh, for a mapwhile construct in Perl.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

      Thanks - I really gotta bone up on use and abuse of 'map'.

        Outta interest.

        1. Did you mean to imply that all the subarray in the input had exactly 3 elements?
        2. Is modifying the input in-place okay?

        With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.

        The start of some sanity?