Operating System - HP-UX
1835200 Members
2351 Online
110077 Solutions
New Discussion

Re: Perl script to add comma if...

 
SOLVED
Go to solution
Ratzie
Super Advisor

Perl script to add comma if...

Thanks to the many that help with my script I have know been able to get it to working order.

There is something that I still need to do with it...
Sometimes I may have a column with empty data. I need to insert a comma there. (For a deliminated file)
So after all is said and down the script produces this output...

5555642,00 0 00 18,CUSTOMER HAS
5555656,MATCHING CUTTELN
5555661,00 0 06 08,TELN NOT

I need to put an if statement after my script..
while (<>) {
chomp; # Will remove the leading , or new line
s,^\s+,,; #Remove leading spaces
my @cols=split m/\s{2,}/, $_, -1; # Split on two (or more) white space characters
print join (',',@cols)."\n";
}

That will, if 7digits (together), comma then characters, add a comma.

So the output will look like this...
5555642,00 0 00 18,CUSTOMER HAS
5555656,,MATCHING CUTTELN
5555642,00 0 00 18,CUSTOMER HAS
4 REPLIES 4
Fred Ruffet
Honored Contributor

Re: Perl script to add comma if...

If I really understand, your script ends with 3 fields lines and 2 fields lines. For these ones, you want to insert an empty field between one and two...

here it is (to put before print) :
@cols=($cols[0],"",$cols[1]) if $#cols=1;

regards,

Fred
--

"Reality is just a point of view." (P. K. D.)
H.Merijn Brand (procura
Honored Contributor
Solution

Re: Perl script to add comma if...

Fred, better to write that using splice

@cols == 2 and splice @cols, 1, 0, "";


==>

while (<>) {
chomp; # Will remove the TRAILING optional new line
s/^\s+//; #Remove leading spaces
my @cols = split m/\s{2,}/, $_, -1; # Split on two (or more) white space characters
@cols == 2 and splice @cols, 1, 0, "";
print join (",", @cols), "\n";
}

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Fred Ruffet
Honored Contributor

Re: Perl script to add comma if...

Procura,

I never noticed that a 0 length in splice inserts elements... You are a living perldoc ! Are you eating a camel every morning for breakfast ? :)

Best regards,

Fred
--

"Reality is just a point of view." (P. K. D.)
Ratzie
Super Advisor

Re: Perl script to add comma if...

Thanks