bgaber has asked for the wisdom of the Perl Monks concerning the following question:
If string is 'FBD' I want output to be F, B, D
I thought s/(\d)/$1,/g would work?
Re: Insert comma after every character
by Ratazong (Monsignor) on Apr 21, 2010 at 13:45 UTC
|
my $str = "ABCDE";
print join(",",split(//,$str));
The code above enters a comma after every character, except the last one (as shown in your example). However it does not distinguish if your character is between [A..Za..z].
If you want to stick to your solution (using a regex), replace \d by \w. (\d is for numbers.) However your solution adds a comma after the last character.
HTH, Rata
| [reply] [d/l] [select] |
Re: Insert comma after every character
by choroba (Cardinal) on Apr 21, 2010 at 13:52 UTC
|
\d stands for digit. You might rather use this expression:
s/(?=.)(?<=.)/,/g
It places a comma between any two characters but not at newlines or start/end of string as
s//,/g
would do. | [reply] [d/l] [select] |
Re: Insert comma after every character
by johngg (Canon) on Apr 21, 2010 at 14:01 UTC
|
knoppix@Microknoppix:~$ perl -E '
> $str = q{ABCDEFG};
> substr $str, $_, 0, q{,} for reverse 1 .. length( $str ) - 1;
> say $str;'
A,B,C,D,E,F,G
knoppix@Microknoppix:~$
I hope this is useful.
| [reply] [d/l] |
Re: Insert comma after every character
by chuckbutler (Monsignor) on Apr 21, 2010 at 15:08 UTC
|
If the result is to have a comma after each character, save the last one:
$perl -we "($_='FBD') =~ s/(.)(?!$)/$1,/g; print;"
~~Output~~
F,B,D
the assertion of any character with a zero assertion of not at the end of line should do fine.
Good luck. -c
Update: fixed typo...
| [reply] [d/l] |
Re: Insert comma after every character
by Cristoforo (Curate) on Apr 21, 2010 at 20:35 UTC
|
Another way to do this would be using the substitution operator with \B.
C:\perlp>perl -e "$_='FBD';s/\B/, /g;print"
F, B, D
| [reply] [d/l] [select] |
Re: Insert comma after every character
by JavaFan (Canon) on Apr 21, 2010 at 14:18 UTC
|
So, you have "F", "B", a space, "D" and want to turn that into "F", comma, space, "B", comma, space, "D"? The simplest way is:
$str = "F, B, D" if $str eq "FB D";
Are we free to generalize this? Here's a broad generalization:
$str = "F, B, D";
Or do you want something else? Perhaps you can describe it, instead of assume we're all omniscient, and can deduce what you want from a single example, and some botched code. | [reply] [d/l] [select] |
|
| [reply] |
|
|