#!usr/bin/perl use strict; open FH, "/home/test1/hello.csv" or die; my @array,@array1; #----------I'm pushing all abc's and def's data into respective arrays--------------------------- while() { if ($_=~/^abc/) { push(@array,$_); } elsif($_=~/^def/) { push(@array1,$_); } } #----------I'm writing only one for loop for abc, it will be same for def too. ------------------------------ my @hello; foreach my $i(0..$#array-1) { #-------below code: it splits the second abc and and so on. i.e., strips second abc from the digits.------------------- @hello=split /^\w+\,/,$array[$i+1]; foreach my $j(0..$#hello) { #--------below code:this is for replacing \n of first abc,2,3,4,5,6 with a comma ( ex: abc,2,3,4,5,6, ) $array[$i]=~s/\n/,/g; #--------------below code:here it concatenates the data ( data should look like: 2,3,4,5,6,7,5,2,1,6,2,3,8,2,1,3,1,4 )---------- abc,$array[$i]=$array[$i].$hello[$j]; print $array[$i],"\n"; } } # In my above code, the data is concatenated as follows: abc,2,3,4,5,6 ,7,5,2,1,6,2,3 ,8,2,1,3,1,4 #But expected output is : abc,2,3,4,5,6,7,5,2,1,6,2,3,8,2,1,3,1,4