tkguifan has asked for the wisdom of the Perl Monks concerning the following question:

# input my $input = 'r k r'; # desired output: my $output = 'r3k2r';
  • Comment on How can I replace space sequences in a string with the number of spaces in each sequence?
  • Download Code

Replies are listed 'Best First'.
Re: How can I replace space sequences in a string with the number of spaces in each sequence?
by choroba (Cardinal) on Feb 04, 2015 at 11:25 UTC
    Use the /e modifier to include code in the replacement part of the substitution:
    $input =~ s/( +)/length $1/ge;
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Ingenious. I thought it has something to do with pack-unpack ( which I fear ).
      By the way: what's your solution, if you have to do the same, but with 8 character blocks. So decompose the string into 8 character blocks ( it is promised that its length is an integer multiple of 8 ), and make the substitution within each block, the blocks separated by '/'.
      my $input = 'r k rpp pp'; my $output = 'r3k2r/pp4pp';

        I would nest regexes by calling a function on each 8block.

        How would you implement it ?

        update

        Or

      • split 8 blocks to array
      • replace whitespace for each element
      • join array with separator

        Can be done in a one liner with map .

        Cheers Rolf

        PS: Je suis Charlie!

Re: How can I replace space sequences in a string with the number of spaces in each sequence?
by LanX (Saint) on Feb 04, 2015 at 11:28 UTC
    Something like s/(\s+)/length($1)/ge ?

    This is untested code, please show some effort applying, questioning and understanding it.

    Cheers Rolf

    PS: Je suis Charlie!