We help IT Professionals succeed at work.

how to merge arrays

VSK
VSK asked
on
Hi all!
I have the folloving problem:
in file xy.dat is stored two column data
in file z.dat is stored one column data
how to merge these data in one file xyz.dat?
the number of rows is the same in both files
Comment
Watch Question

Kim RyanIT Consultant

Commented:
file a is
1 2
4 5
7 8

file b is
3
6
9

This will give you an array of
1 2 3
4 5 6
7 8 9

Note that each row in the array is just a string of 3 numbers. You can write this back to a new file. Not sure if you want data loaded into a 2 dimensional array as well.


open(FH1,"<a.txt") or die;
open(FH2,"<b.txt") or die;

while (<FH1>) {
  chomp;
  push(@file_a,$_);
}
while (<FH2>) {
  chomp;
  push(@file_b,$_);
}
close(FH1);
close(FH2);


$num_rows = scalar(@file_a);
foreach  $row (0.. $num_rows - 1) {
  $joined_line = $file_a[$row] . ' ' .  $file_b[$row];
  push(@file_c,$joined_line);
}

foreach $row (@file_c)
{
  print "$row\n";
}
open(FH1,"<zy.dat") or die;
open(FH2,"<z.dat") or die;

chomp @ab = <FH1>;
chomp @c =  <FH2>;
my @abc;

close(FH1);
close(FH2);


for (0..$#ab) {
     $abc[$_] = $ab[$_]."\t".$c[$_];
}


###2. faster way using less RAM will be
### to add the vals to @ab instaed creating new array

for (0..$#ab) {
     $ab[$_] .= "\t".$c[$_];
}



### To save new dat file

open(FH,">xyz.dat") or die;
print FH, @abc; ## ar ab if using 2
close FH;







EXPLANATION :
##########################################################

### $#ab - the index of the last element in @ab
for (0..$#ab) {
### if @ab has 300 elements this is eq to for(0..299)

### $_ - the current element from array (0..299)
     $abc[$_] = $ab[$_]."\t".$c[$_];
### if curren $_ = 3 for exaple this will be :
     $abc[3] = $ab[3]."\t".$c[3];

}
### $ab[3]."\t".$c[3] means:
concat (join) to strings
($ab[3]- the value of 3rth el from @ab + $c[3]- the value of 3rth el from @c)
and return one whole string ($abc[3])


VSK

Author

Commented:
Thank's.
Sorry for delay - was problems to connect to exp-exchange.
Thanks ! :))
just pleeease tell me why "B" ?

;)

Explore More ContentExplore courses, solutions, and other research materials related to this topic.