sub words_before { my ( $word, $string ) = @_; my ( $before ) = $string =~ m/(.*?)\Q$word\E/g; my $words_before = () = $before =~ m/(\S+)/g; return $words_before; } #### print 'There are ' . words_before( $word, $string ) . ' words before "' . $word . '" in the string "' . $string . '"' . "\n";