[Israel.pm] using split and join to add a characters every 2 original ones
sawyer x
xsawyerx at gmail.com
Sun Nov 2 06:32:13 PST 2008
You could fix that join with map
print map { $_ || '#' } split /(.{2}/, "For example";
But split() still puts the spaces before instead of after when you use
rounded brackets: ().
The closest I got (sort of cheating but still quite short):
$ perl -le'print join "", map { $_ && "$_#" } (split /(.{2})/, "For example");'
Fo#r #ex#am#pl#e#
The only difference is that it adds the character to the end because
it's still a valid input and not space.
I guess you could chop it like this in the end:
$ perl -le'$str = join "", map { $_ && "$_#" } (split /(.{2})/, "For
example"); chop $str if length $str % 2; print $str'
Fo#r #ex#am#pl#e
But it does make it longer.
On Sun, Nov 2, 2008 at 3:48 PM, Yossi Itzkovich
<Yossi.Itzkovich at ecitele.com> wrote:
>
> Hi,
>
> I was asked by a friend to write a one-linear to add a character every 2 characters. For example:
> "For example" Will become "Fo#r #ex#am#pl#e"
>
> I tried to do it with join and split (seems natural for me), but had no success, I managed to do it only with map:
> map({s/(..)/$1#/g,$_}$_)
>
> The best I got from join and split is :
> join ("#" , split (/(..)/, $_))
> which prints 2 # after each 2 characters. I understand why, but I could not get rid of it.
>
> Any ideas ?
>
> Yossi
>
>
>
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl
More information about the Perl
mailing list