http://www.perlmonks.org?node_id=952812


in reply to Regular Expression Search

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.