http://qs321.pair.com?node_id=268820

Earlier in the CB, jepri asked about how to best collapse repetitive data within some input stream, and this turned into a nice display of intuitive and expensively backtracking regular expressions. I thought a bit more about the problem and made up some more restrictions :

Given a line on STDIN, that line should have "some" repetitions removed, starting with the leftmost repeating sequence. Examples:

foofoofoo -> Sequence is foo 123456 -> no Sequence ooofoofoofoof -> First sequence is o

The output of a sequence must consist of the shortest sequence plus the repeat count. Example:

foofoofoofoo -> foo repeated 4 time(s) # correct foofoofoofoo -> foofoo repeated 2 time(s) # wrong

If there is stuff that fits in no sequence, it is to be output as well. Example:

123456 -> 123456

The parts of the string are then to be output as they appear within the string. Example for input foofooofooo :

foo repeated 2 time(s) o f o repeated 3 time(s)

This method is not always optimal, as it does not always find the overal shortest decomposition into sequences and nonsequences in the case that a better match is overlapped by a sequence starting closer to the left - this comes from the specification and the nature of the Perl regular expression engine, which favours the leftmost match over the longest match.

My try at this problem is at 124 chars (discounting whitespace and the command line invocation(11 chars)):

perl -nle 'printf(defined $3 ? "%s\n" : "%s repeated %s time(s)\n", $1.$3, length($2)/length($1.$3)+1) while/(?:(\w+?)(\1+))|(?:(\w+?)(?!\3))/g'
__END__ perl -MHTTP::Daemon -MHTTP::Response -MLWP::Simple -e ' ; # The $d = new HTTP::Daemon and fork and getprint $d->url and exit;#spider ($c = $d->accept())->get_request(); $c->send_response( new #in the HTTP::Response(200,$_,$_,qq(Just another Perl hacker\n))); ' # web