%%
%% This is file `example.tex',
%% generated with the docstrip utility.
%%
%% The original source files were:
%%
%% perltex.dtx  (with options: `example')
%% 
%% This is a generated file.
%% 
%% Copyright (C) 2010 Scott Pakin <scott+pt@pakin.org>
%% 
%% This file may be distributed and/or modified under the conditions of
%% the LaTeX Project Public License, either version 1.3c of this license
%% or (at your option) any later version.  The latest version of this
%% license is in:
%% 
%%    http://www.latex-project.org/lppl.txt
%% 
%% and version 1.3c or later is part of all distributions of LaTeX version
%% 2006/05/20 or later.
%% 
\documentclass{article}
\usepackage[optional]{perltex}
\usepackage{environ}
\usepackage{hyperref}

\ifperl

  \perlnewcommand{\dolinkwords}[3]{
      # Preprocess our arguments.
      $url = $_[0];
      $url =~ s/\\\%s/\%s/g;
      %stopwords = map {lc $_ => 1} split " ", $_[1];
      $stopwords{""} = 1;
      $text = $_[2];

      # Replace LaTeX code in the text with placeholders.
      $placeholder = "ABCxyz123";
      %substs = ();
      $replace = sub {$substs{$placeholder} = $_[0]; $placeholder++};
      $text =~ s/\\(begin|end)\s+\{[a-z]+\}/$replace->($&)/gse;
      $text =~ s/\\[a-z]+/$replace->($&)/gse;

      # Hyperlink each word that's not in the stop list.
      $newtext = "";
      foreach $word (split /((?<=[-\A\s])[\'a-z]+\b)/i, $text) {
          $lcword = lc $word;
          if (defined $stopwords{$lcword} || $lcword =~ /[^a-z]/) {
              $newtext .= $word;
          }
          else {
              $newtext .= sprintf "\\href{$url}{%s}", $lcword, $word;
          }
      }

      # Restore original text from placeholders and return the new text.
      while (($tag, $orig) = each %substs) {
          $newtext =~ s/\Q$tag\E/$orig/gs;
      }
      return $newtext;
  }

  \NewEnviron{linkwords}[2][]{\dolinkwords{#2}{#1}{\BODY}}{}

\else

  \newenvironment{linkwords}[2][]{}{}

\fi

\begin{document}

\newcommand{\stopwords}{a an the of in am and or but i we me you us them}

\begin{linkwords}[\stopwords]{http://www.google.com/search?q=define:\%s}
\begin{verse}
  I'm very good at integral and differential calculus; \\
  I know the scientific names of beings animalculous:  \\
  In short, in matters vegetable, animal, and mineral, \\
  I am the very model of a modern Major-General.
\end{verse}
\end{linkwords}

\end{document}
\endinput
%%
%% End of file `example.tex'.
