• Status: Solved
• Priority: Medium
• Security: Public
• Views: 232

# Add columns to 2D array

I want to take certain columns from @ary1 and @ary2 and add them to the @master array.  I can do this easily if I added as rows but I want to add as columns.  What is a generic method for doing this?  The columns need to be added one at a time.

@ary1 = (
[1,2,3,4],
[2,3,4,5],
[3,4,5,6],
[4,5,6,7]
);

@ary2 = (
[2,4],
[4,8],
[0,0],
[0,0]
);

# After adding columns 0 and 1 from @ary1 and column 1 from @ary2, this should be the result.
# We'll go ahead and assume that the number of rows of @ary1 and @ary2 are the same.
@master = (
[1,2,4],
[2,3,8],
[3,4,0],
[4,5,0]
);
0
mock5c
1 Solution

Commented:
Tested this and it works. From1 defines the columns you want from 1, from 2 defines the columns from 2. This assumes that each has the same number of rows, and that there are only 2 arrays to concatenate. However, it should be easy enough to extend.

\$size = @ary1;
@from1 = (0,1);
@from2 = (1);

my @master;
my @row;
for(\$i = 0; \$i < \$size; \$i++) {
foreach my \$column (@from1) {
push(@row, \$ary1[\$i][\$column]);
}
foreach my \$column (@from2) {
push(@row, \$ary2[\$i][\$column]);
}

\$master[\$i] = [@row];
@row = ();
}

0

Commented:
@master = map{[@{\$ary1[\$_]}[@from1],@{\$ary2[\$_]}[@from2]]}0..\$#ary1;
0

## Featured Post

Tackle projects and never again get stuck behind a technical roadblock.