in reply to stack array to array of arrays

> It would be fun to be able to do this in-line without a sub

DB<119> @a=a..e => ("a", "b", "c", "d", "e") DB<120> map [splice @a,0,3], 0..$#a/3 => (["a", "b", "c"], ["d", "e"])

but beware of the case @a=()

> Anyone have a cool way to do this?

not really :(

Cheers Rolf

( addicted to the Perl Programming Language)

Replies are listed 'Best First'.
Re^2: stack array to array of arrays
by spandox (Novice) on Oct 17, 2013 at 14:18 UTC
    I like this because it is small - HOWEVER it is destructive of the original array. It does often work for me though. in my code it looks like
    my @array = qw(0 a b c e 1 2 3 4 5 3 f w); my $len = 4; print oxTable->new([ map [splice @array,0,$len], 0..$#array/$len ]);
    Produces
    +--+--+--+--+ |0 |a |b |c | |e |1 |2 |3 | |4 |5 |3 |f | |w | | | | +--+--+--+--+
      > I like this because it is small

      I don't like it, IMHO it's

      1. hard to read golfing!
      2. not DRY
      3. and furthermore buggy in edge cases.

      you might get used to it, but the next one to maintain your code wont be "pleased".

      > It does often work for me though.

      Look! If you need it often, so why don't you just use your custom routine?

      Just compare the overhead to document this hack with just encapsulating all the infos in a sub!

      Or use something from List::MoreUtils ?

      DB<117> use List::MoreUtils qw/part/; DB<118> my $i; part {$i++ %3} a..h => (["a", "d", "g"], ["b", "e", "h"], ["c", "f"]) DB<119> use feature 'state'; part {state $i++ %3} a..h => (["a", "d", "g"], ["b", "e", "h"], ["c", "f"])

      update

      oops sorry, this transposed the matrix, corrected code:

      DB<139> use feature "state"; part {state $i++/3} a..h => (["a", "b", "c"], ["d", "e", "f"], ["g", "h"])

      Cheers Rolf

      ( addicted to the Perl Programming Language)

        ooooh - I like it; when it comes to the actual call it is small.
        use feature 'state'; use List::MoreUtils qw(part); ... print oxTable->new([ part { state $i++ / $len } @array ]);
        My problem is that it requires a lot of extra includes...
        It also breaks down on the same edge ($len = 0);
        It also requires a temp variable.
        It may be worth it to just stay with.
        sub arrayStack { my $len= pop; return map [splice @_,0,$len], 0..$#_/$len; } ... print oxTable->new([ arrayStack(@array,$len) ])

        But it was a worthy exercise.... I actually never thought to use a counter as the inputted array and splicing off of the named array.