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
/es///willevaluate 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
$2means 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
- with
- the
whileloop continues until $_ is empty - once
$_is empty and all the text is processed,$ois assinged to$_so it's printed.
Todo:
- remove
$o, by usingprint, 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