[Buffalo-pm] Question: How to iterate through 2 arrays andmerge columns

Jim Brandt cbrandt at buffalo.edu
Wed Jul 6 05:11:39 PDT 2005


I think my example mixed a few variable names as well, and that may  
have confused things.

Looking at your original code, you are doing:

> push(our @red_elements,
> ($red_items[6], "\t", $red_items[7], "\t",
> $red_items[8], "\t", $red_items[9], "\n"
> )
> );

The parentheses (which I didn't see before) will create an anonymous  
array in each element of @red_elements. This can work for you since  
you've created a 2-dimensional array, which is really a table. So I  
think if you modify my code to do this:

for (my $j=0;$j<=$#red_elements;$j++){
   # Iterate through outer loop, one row at a time.
   for ( my $i=0; $i <= 7; $i++ ){
     # You have eight columns, so this will go through each column  
and print it.
     print OUTFILE $red_elements[$j][$i];
   }

   # Repeat for green_elements.
   for ( my $i=0; $i <= 7; $i++ ){
     # You have eight columns, so this will go through each column  
and print it.
     print OUTFILE $green_elements[$j][$i];
   }

} # End outer loop.

Note that you'll need to modify your code building the red_elements  
since you are currently putting a new line as the last element and I  
think you want a tab.

That should work, but is a bit convoluted. I would simplify your  
earlier step to make it just a string rather than 8 elements in an  
array. For example:

push(our @red_elements, $red_items[6] . "\t" . $red_items[7] . "\t" .  
$red_items[8] . "\t" . $red_items[9] . "\t" );

The dot is the string concatenation operator, so it will push all of  
that together into a single string. I think if you do it this way, my  
first example will work.

Basically, it's playing with data structures two different ways.

For what it's worth, I think Kevin's suggestion was the quickest and  
cleanest, but you don't get to play with data structures in perl. :)

Good luck.

Jim

On Jul 5, 2005, at 10:33 PM, Shankar, Ganesh wrote:

> Your suggestions were on the right track but maybe I wasn't clear  
> as to what I wanted.  I need 4 cols from red followed by 4 cols  
> from green.  The following code gives me 4 pairs of red(no space) 
> green(tab)(tab).
>
> I tried:
> <code>
>     for (my $j=0;$j<=$#red_items;$j++){
>     push(@intermediate, $red_items[$j],$green_items[$j]);
>     }
> print OUTFILE @intermediate;
> </code>
>
> What results is:
> $red_items[6](no space)$green_items[6](2 tabs)$red_items[7](no  
> space)$green_items[7]
> (2 tabs)$red_items[8](no space)$green_items[8](2tabs)$red_items[9] 
> (nospace)$green_items[9]

==========================================
Jim Brandt
Administrative Computing Services
University at Buffalo



More information about the Buffalo-pm mailing list