in reply to count repeatation

There are more than one way to do this.
#!/usr/bin/perl use strict; my $string = 'ab23cdefgXX(3A5)XXhijkl23mnXX(3)XXopq432rsXX(450b)XXtuv' +; my @counts = split( "XX", $string ); print $#counts;

Replies are listed 'Best First'.
Re^2: count repeatation
by JavaFan (Canon) on Aug 19, 2009 at 16:14 UTC
    That doesn't always provide the correct results.
    my $string = "XXXX"; my @count = split( "XX", $string ); print $#count; # Prints -1
    One could fix that by giving split third argument.

    But it doesn't scale to generic patterns. Suppose you want to count how after characters are repeated (so, count not only "XX", but also "AA", "22", "--", etc). A pattern /(.)\1/ matches that, but

    my $string = "XXYY"; my @count = split( /(.)\1/, $string, -1 ); print $#count; # Prints 4, not 2.
    The reason is that if the pattern in contains capturing parenthesis, split returns what's captured in the parens as well.