title: Unable to replace a pattern in the same string with Perl
body: <p>I want to change <code>&lt;a&gt;</code> tags to external links in a HTML text (not a full HTML document). Nevertheless, this Perl program fails to replace a pattern if the pattern occurs multiple times in the same line of string.</p>
  <p>Here is a sample program:</p>
  <pre class="lang-perl prettyprint-override"><code>use strict;
  use warnings;
  
  my $baseURL = &quot;https://example.com&quot;;
  my $input = &lt;&lt;'END';
  &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;https://www.amazon.com&quot;&gt;Amazon&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;
          &lt;!-- Keep it in one line. --&gt;
          &lt;a href=&quot;https://www.google.com.tw&quot;&gt;Google&lt;/a&gt; and &lt;a href=&quot;https://tw.yahoo.com&quot;&gt;Yahoo&lt;/a&gt; and &lt;a href=&quot;https://duckduckgo.com&quot;&gt;DuckDuckGo&lt;/a&gt;
      &lt;/li&gt;
  &lt;/ul&gt;
  END
  
  # Replace external links globally.
  $input =~ s{&lt;a href=\&quot;([^&quot;]+)\&quot;&gt;(.+)&lt;/a&gt;}{
      # Skip local URIs.
      substr($1, 0, 4) ne &quot;http&quot; ? &quot;&lt;a href=\&quot;$1\&quot;&gt;$2&lt;/a&gt;&quot;
      # Skip links in same domain.
      : index($1, &quot;$baseURL&quot;) &gt;= 0 ? &quot;&lt;a href=\&quot;$1\&quot;&gt;$2&lt;/a&gt;&quot;
      # Disable search engines from following links.
      : &quot;&lt;a href=\&quot;$1\&quot; target=\&quot;_blank\&quot; rel=\&quot;noopener nofollow\&quot;&gt;$2&lt;/a&gt;&quot;}ge;
  
  # Print modified input to STDOUT.
  print $input;
  </code></pre>