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

Hi again (this is question 2 out 3 for today...),
is there any nice way of removing a column from somewhere in the middle of a two-dimensional array. Also, can a similar principle can be used to shuffle columns around?
Thanks a lot!
  • Comment on Splice equivalent for a two-dimensional arrays

Replies are listed 'Best First'.
Re: Splice equivalent for a two-dimensional arrays
by ikegami (Patriarch) on Jul 14, 2006 at 15:36 UTC

    There's no such thing as a two dimentional array in Perl per say. That means you have to remove elements from multiple row arrays. That means you need a loop. Loop over every row, and splice the offending column from the referenced row array.

    # Remove the 4th column. splice(@$_, 3, 1) foreach @$rows;

    Update: Two swap two columns, use splice to remove one, and use splice to reinsert it at the new location.

    # Swap the 3rd and 4th columns. splice(@$_, 2, 0, splice(@$_, 3, 1)) foreach @$rows;

    Alternatively, create a translation map and use an array slice:

    # Swap the 3rd and 4th columns. my @map = (0, 1, 3, 2, 4, 5); @$_ = @$_[@map] foreach @$rows;
Re: Splice equivalent for a two-dimensional arrays (col shuffle)
by tye (Sage) on Jul 14, 2006 at 15:40 UTC

    To shuffle columns (assuming rectangular data):

    my @idx= 0..$#{$aoa[0]}; Shuffle( \@idx ); for my $av ( @aoa ) { @$av= @$av[@idx]; }

    - tye