Getting the words from the character offsets is easy enough with
substr. Here's an easily adaptable way to count the words before a particular word in a string for a sufficiently simple definition of 'word':
sub words_before {
my ( $word, $string ) = @_;
my ( $before ) = $string =~ m/(.*?)\Q$word\E/g;
my $words_before = () = $before =~ m/(\S+)/g;
return $words_before;
}
This can be used such as this:
print 'There are ' . words_before( $word, $string ) . ' words before "
+' . $word . '" in the string "' . $string . '"' . "\n";
The word index counting from 0 is the same as the number of words before the given word. Counting from 1, you'll need to add one to that amount.