in reply to group things?

I know how to split the string and read it letter by letter, doing something like:
$str="-----MMMMM------IIIII----MMM---OOOO---I---MMMM-----"; @my_splitted_str=split("",$str);
My problem is how will Perl "understand" that, for instance letters 6-10 are M and print 6-10:M and not 6:M, 7:M, 8:M, 9:M, 10:M?

Replies are listed 'Best First'.
Re^2: group things?
by FunkyMonk (Bishop) on Apr 25, 2008 at 22:39 UTC
    Joost's given you a solution using regexps. Here's one using split:
    my $str = '-----MMMMM------IIIII----MMM---OOOO---I---MMMM-----'; my ( $start, $end ); for ( split /(-+)/, $str ) { my $char = substr $_, 0, 1; next unless length; # WTF does split return an empty string at the + start if ( $char ne '-' ) { print $start+1, length > 1 ? ( "-", $start + length ) : "", ": $char\n" } $start += length; }

    Output:

    6-10: M 17-21: I 26-28: M 32-35: O 39: I 43-46: M


    Unless I state otherwise, my code all runs with strict and warnings
Re^2: group things?
by ysth (Canon) on Apr 25, 2008 at 23:04 UTC
    One way:
    use strict; use warnings; my $str="-----MMMMM------IIIII----MMM---OOOO---I---MMMM-----"; my @my_splitted_str=split(//,$str); # add a sentinel value after the other characters, so # the end of the last range is properly detected push @my_splitted_str, "-"; my $range = ""; # we are not initially in a range my $start_of_range; for my $index ( 0 .. $#my_splitted_str ) { # if we are in a range, see if it ends now if ( $range && $range ne $my_splitted_str[$index] ) { # the previous character was the last of this range my $end_of_range = $index - 1; if ($end_of_range == $start_of_range) { print $start_of_range + 1, ":", $range, "\n"; } else { print $start_of_range + 1, "-", $end_of_range + 1, ":", $r +ange, "\n"; } $range = ""; } # see if this is the start of a range if (! $range && $my_splitted_str[$index] ne "-") { $start_of_range = $index; $range = $my_splitted_str[$index]; } }