Boetsie has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,

i have some large strings with character 'N' within it, the patterns are like;

xxxxxxxNNNNNxxxxxNxxxxNNNNNNNNxxx

xxNxxxNNNNNNNNNxxxxxx

etc...

For each string, i want the number of consecutive N's. So for the first string I want the numbers 5, 1 and 8. The second string I want the numbers 1 and 9.

Anyone knows how to do this?

Cheers, Marten

Replies are listed 'Best First'.
Re: count consecutive characters
by moritz (Cardinal) on Jun 07, 2010 at 08:38 UTC
    Untested:
    while ($str =~ /(N+)/g) { print length($1), "\n"; }

    See perlretut and maybe perlre for an explanation.

    (Updated after reading the question more carefully this time)

Re: count consecutive characters
by johngg (Canon) on Jun 07, 2010 at 09:28 UTC

    A similar approach to moritz's but using a map instead of a while loop to take advantage of the default behaviour of length to operate on $_.

    $ perl -E ' > @strs = qw{ > xxxxxxxNNNNNxxxxxNxxxxNNNNNNNNxxx > xxNxxxNNNNNNNNNxxxxxx > }; > foreach $str ( @strs ) > { > print qq{$str : }; > say join q{, }, > map length, $str =~ m{(N+)}g; > }' xxxxxxxNNNNNxxxxxNxxxxNNNNNNNNxxx : 5, 1, 8 xxNxxxNNNNNNNNNxxxxxx : 1, 9 $

    I hope this is useful.

    Cheers,

    JohnGG

    Update: Changed second print statement to a say and got rid of the say with no arguments. What was I thinking?

Re: count consecutive characters
by Boetsie (Sexton) on Jun 07, 2010 at 09:54 UTC
    Thanks both for replies, i've implemented Moritz method since it worked :) Thank you!