Add columns to 2D array

Posted on 2006-05-24
Last Modified: 2008-03-17
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 = (

@ary2 = (

# 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 = (
Question by:mock5c
    LVL 1

    Accepted Solution

    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 = ();

    LVL 84

    Expert Comment

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

    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    Join & Write a Comment

    Many time we need to work with multiple files all together. If its windows system then we can use some GUI based editor to accomplish our task. But what if you are on putty or have only CLI(Command Line Interface) as an option to  edit your files. I…
    There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

    730 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now