Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Splitting on change

by thor (Priest)
on Dec 08, 2005 at 16:15 UTC ( #515284=perlquestion: print w/ replies, xml ) Need Help??
thor has asked for the wisdom of the Perl Monks concerning the following question:

Greetings all,

The other day, I found myself in the position to split a string not on an explicit delimiter, but rather where the string changes. A quick example might be in order:

my $x = "AAAABBBCCCCCC"; my $regex = qr(); #this is my hang-up! my @x = split($regex, $x); #I want @x = ("AAAA", "BBB", "CCCCCC")
I've gotten close. For my regex, I have thus far qr((?:(\w))(?!\1)+). This produces an array of qw(AAA A BB B CCCCCC). The problem as I see it is the following passage from perldoc -f split:
If the PATTERN contains parentheses, additional list elements are created from each matching substring in the delimiter.
However, I don't see how I can get around using capturing parentheses given that I have to use a back reference in the regular expression. Does anyone have any experience with this problem?

thor

The only easy day was yesterday

Comment on Splitting on change
Select or Download Code
Re: Splitting on change
by Roy Johnson (Monsignor) on Dec 08, 2005 at 16:19 UTC
Re: Splitting on change
by Fletch (Chancellor) on Dec 08, 2005 at 16:25 UTC

    Kludgy, but you could use what you've got and append every even element to the preceding odd element.

    my @result; while( my( $o, $e ) = splice( @tmp, 0, 2 ) ) { push @result, $o . $e } print join( "\n", @result ), "\n";

    Update: Bleh, ignore me. Look at the other suggestions. Now where'd my caffeine go . . .

Re: Splitting on change
by ikegami (Pope) on Dec 08, 2005 at 16:25 UTC
    my $t = 0; my @x = grep $t^=1, split /(?<=(.))(?!\1)/, $x;
    my @x; push(@x, $1) while $x =~ /((.)\2*)/g;
    my $t = 0; my @x = grep $t^=1, $x =~ /((.)\2*)/g;
    my $t = 0; my @x = grep $t^=1, map /((.)\2*)/g, $x;

    $t is for "toggle". grep is used to filter out every second item.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://515284]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2014-12-20 12:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (95 votes), past polls