Others have already shown you a better way to go, but here's an implementation using index just for fun:

#!/usr/bin/perl use strict; use warnings; sub find_char { my ($char, $string) = @_; my @indexes_present = (); my $position = 0; while (length($string)) { my $index = index($string, $char); if ($index != -1) { $position = $position + ($index+1); push @indexes_present, $position; $string = substr($string, ($index+1), (length($string)-$in +dex)); } else { last; } } push @indexes_present, -1; my ($start_of_range, $end_of_range); my $previous_index; while (my $index = shift @indexes_present) { if (!defined($previous_index)) { $start_of_range = $end_of_range = $index; } elsif (($previous_index+1) == $index) { $end_of_range = $index; } else { if ($start_of_range == $end_of_range) { print "Found at $start_of_range\n"; } else { print "Found at $start_of_range to $end_of_range\n"; } $start_of_range = $end_of_range = $index; } $previous_index = $index; } } while (<DATA>) { print "\n$_"; find_char('-', $_); } __DATA__ A--B---C----D-E A-B--C---D----E ---------------

Prints:

A--B---C----D-E Found at 2 to 3 Found at 5 to 7 Found at 9 to 12 Found at 14 A-B--C---D----E Found at 2 Found at 4 to 5 Found at 7 to 9 Found at 11 to 14 --------------- Found at 1 to 15 Press ENTER or type command to continue

So yeah. The other way is better.


In reply to Re: Regular Expression Search by Riales
in thread Regular Expression Search by Monk007

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.