capser capser - 1 month ago 8
Perl Question

Perl formatting array output.

I have a small program that I am trying to format the output.
The results get loaded in to an array - I am just having trouble formating the
printing out the array into a certain format.

#!/usr/bin/perl
use strict ;
use warnings ;
my @first_array ;
my @second_array ;
my @cartesian ;

while (<>) {
my $first_input = $_ ;
@first_array = split(' ', $first_input) ;
last ;
}
while (<>) {
my $second_input = $_ ;
@second_array = split(' ', $second_input) ;
last ;
}


while(my $first=shift(@first_array)) {
push(@cartesian, $first) ;
my $second = shift(@second_array) ;
push(@cartesian, $second ) ;

}

print "This is the merged array: @cartesian\n" ;


When I enter this in, I get this:

$ ./double_while2.pl
1 2 3
mon tue wed
This is the merged array 1 mon 2 tue 3 wed


what I want to print out is :

"1", "mon",
"2", "tue" ,
"3", "wed",


or alternately:

1 => "mon",
2 => "tue",
3 => "wed,

Answer

Try to use hash instead.

for my $i(0..$#first_array){
    $hash{$first_array[$i]} = $second_array[$i];
 }

or else, you want format without using hashes, try as follows

for  (my $i = 0; $i < $#cartesion/2; $i++) {
      my $j  = ($cartesion/2) + $i;
      print "$cartesion[$i] $cartesion[$j] \n";

   } 
Comments