I did a hacker-rank thing about run-length encoding, after hitting submit I realised there was more golfing to be done:

me@compy-386:~ echo "aaaabcdeeee" | perl -plE '
s/^(.)(\1*)/$o.= $1.($2&&length" $2");""/e while $_;
$_=$o
'
a4bcde4

It's nothing too magical:

  • -print each line after -Evaling the expression for each line of the file, with automatic handling of -line endings
  • for each iteration, we match the first character in $_, and the more of them (\1*)
    • with /e s/// will evaluate the replacement as an expression instead of treating it as a plain old string replacement
    • the expression appends the first match $1 (the first letter) and the length of the second match in $2 (the rest of the run) to $o
    • an empty $2 means the length isn't added because the challenge dictated that a single character is left alone ('a' instead of 'a1')
    • the "" is htere so the matched text is replaced with nothing, moving us closer to $_ being empty
  • the while loop continues until $_ is empty
  • once $_ is empty and all the text is processed, $o is assinged to $_ so it's printed.

Todo:

  • remove $o, by using print, or with fancy use of /g.
  • remove the while, I'm sure it can be done.
  • remove "" from the replace.

Standard perl-golf disclaimer

Please don't do this kind of thing in a production code base