Add a space between certain characters Using Perl Scripting

Hello All,

I have a variable which is having values like this..

$var=A,B,C,D,E,F,G,H

I want to add space after every three alphabets so that my final variable should look like this..

$var=A,B,C, D,E,F, G,H

the space should come after the comma of third alphabet..

Pls tell me how to achive this using perl scripting..

Thanks in advance..

 
$ perl a.pl 
A,B,C, D,E,F, G,H
 
$ cat a.pl
#!/bin/perl -w
$var="A,B,C,D,E,F,G,H";
@splitArray=split(/,/,$var);
for($i=0;$i<=scalar(@splitArray);$i=$i+3)
{
        if ($i==0) {next;}
        $splitArray[$i]=" " . $splitArray[$i];
}
print join (",",@splitArray);
1 Like

Thanks Kamaraj.. working fine :slight_smile:

---------- Post updated 05-04-12 at 07:39 AM ---------- Previous update was 05-03-12 at 11:33 PM ----------

Hi I have a small problem here...

the above code is working fine if the no of aplhabets in input variable is not multiple of 3... if it is mutliple of three then it places a comma at the end like this


case 1:

input : $var="A,B,C"   //Only 3 alphabets

output: A,B,C,  // comma not reqd at the end

expected : A,B,C

case2:

input : $var="A,B,C,D,E,F"  // 6 alphabets

output: A,B,C, D,E,F,  // comma not reqd at the end

expected : A,B,C, D,E,F  // a white space after 3 alphabets

case 3: 

input : $var="A,B,C,D,E,F,G,H" // not a multiple of 3

output: A,B,C, D,E,F, G,H  // coming as expected

expected : same as output

pls help me to remove the comma coming at the end

---------- Post updated at 08:22 AM ---------- Previous update was at 07:39 AM ----------

can somebody pls help me

Hi smarty86,

One way:

$ cat script.pl
use warnings;
use strict;

while ( my $var = <DATA> ) {
        chomp $var;
        $var =~ s/((?:[[:upper:]],){3})(?!$)/$1 /g;
        printf qq[%s\n], $var;
}

__DATA__
A,B,C,D,E,F,G,H
A,B,C
A,B,C,D,E,F
$ perl script.pl
A,B,C, D,E,F, G,H
A,B,C
A,B,C, D,E,F