XXX: after context
[perl/list-index.git] / lib / List / Index.pm
index 574613e8b1c38e2e6b3eaf4c751fd42d53c6930e..47ef0da75030c8cda582a1b1bf93d4b9a0db493d 100644 (file)
@@ -28,16 +28,33 @@ sub ranges {
        while ($offset < @$self) {
                my $link = substr $self->[$offset], 0, $length;
                if ($context) {
-                       # take a value slightly before the current offset
-                       my $before = $offset > $context ? $self->[$offset - $context] : '.';
-                       # see how much of it matches the current link
-                       my $trim = 1;
-                       for my $match (split //, $before) {
-                               scalar $link =~ /\G\Q$match/g or last;
-                               $trim++;
+                       {
+                               # take a value slightly before the current offset
+                               my $before = $offset > $context ? $self->[$offset - $context] : '.';
+                               # see how much of it matches the current link
+                               my $trim = 1;
+                               for my $match (split //, $before) {
+                                       scalar $link =~ /\G\Q$match/g or last;
+                                       $trim++;
+                               }
+                               # truncate link upto where the earlier value starts to differ
+                               substr($link, $trim) = '' unless $trim > length $link;
+                       }
+
+                       if ($offset + $context < $#$self) {
+                               # take a value after the current offset
+                               my $after = $self->[$offset + $context];
+                               # see how much of it matches the current link
+                               my $trim = 1;
+                               for my $match (split //, $after) {
+                                       scalar $link =~ /\G\Q$match/g or last;
+                                       $trim++;
+                               }
+                               # use this link if it's shorter
+                               if ($trim < length $link) {
+                                       $link = substr $after, 0, $trim;
+                               }
                        }
-                       # truncate link upto where the earlier value starts to differ
-                       substr($link, $trim) = '' unless $trim > length $link;
                }
 
                push @links, [$link];