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:
-p
rint each line after-E
valing the expression for each line of the file, with automatic handling of-l
ine endings- for each iteration, we match the first character in
$_
, and the more of them (\1*
)- with
/e
s///
wille
valuate 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
- with
- 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 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