my journey on the road to Perl wisdom has led me to your gates. I'm here to present to you a little innocent problem, which nonetheless gave me some pain in thinking about it.
The task which torments me is the following:
"Given a string, e. g. "xx556xx", split it into an array, where the split strikes between every non-identical characters, i. e. getting qw(xx 55 6 xx) from the example string above."
But what is with Perl's promise of "simple things easy"?sub seq1 { my $r; my $r0; my @R; for my $c (split '', shift) { unless (defined $r) { $r = $c; $r0 = $c; } elsif($c eq $r0) { $r .= $c; } else { push @R, $r; $r = $c; $r0 = $c; } } push @R, $r if length $r; @R; }
Let's look at bigger shells then: Regexes:
The 1st line is actually mine, while credit for the 2nd goes to murphy on the German perl-community board, fixing an oversight by me.sub seq2 { my @x = shift =~ m/((.)\2*)/g; map $x[2*$_], 0..@x/2-1; }
This looks quite good, and Benchmark even suggests, that it has a little edge in performance over the for-driven sub.
Alas! it would be perfect, if no postprocessing was necessary on the match expression result!
Oh enlighted monks, is any such "easy expression for the simple problem" laid down in your holy books?
Footnote: granted that readability and elegance are to a great extend functions of individual perception, I was nonetheless frustrated that I could not dig up an "elegant" 1-liner for the described problem so far.
In reply to Elegant way to split into sequences of identical chars? by pKai
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |