title: Perl's odd behavior of index() when called with empty substr with vs without Encode::decode()
body: <p>I have created a very small sample code below to illustrate how Perl's <code>index()</code> function's return value changes for empty <code>substr</code> (&quot;&quot;) on string that is passed or not passed through <code>Encode::decode()</code>.</p>
  <pre><code>use strict;
  use Encode;
  
  my $mainString = (@ARGV &gt;= 2) ? $ARGV[1] : &quot;abc&quot;;
  my $subString  = (@ARGV &gt;= 3) ? $ARGV[2] : &quot;&quot;;
  if (@ARGV &gt;= 1) {
      $mainString = Encode::decode(&quot;utf8&quot;, $mainString);
  }
  
  my $position = index($mainString, $subString, 0);
  my $loopCount = 0;
  my $stopLoop  = 7; # It goes for ever so set a stopping value
  while ($position &gt;= 0) {
      if ($loopCount &gt;= $stopLoop) {
          last;
      }
      $loopCount++;
  
      print &quot;[$loopCount]: $position \&quot;$mainString\&quot; [&quot;.length($mainString).&quot;] ($subString)\n&quot;;
      $position = index($mainString, $subString, $position + 1);
  }
  </code></pre>
  <p>Before getting into with vs without <code>Encode::decode()</code>, what should the return value of <code>index()</code> be for an empty <code>substr</code> (&quot;&quot;) because <a href="https://perldoc.perl.org/functions/index" rel="nofollow noreferrer">Perl's documentation</a> does not mention it. Although it does not mention it, here is the execution result <strong>without</strong> calling <code>Encode::decode()</code> for ASCII characters &quot;abc&quot; (<code>@ARGV = 0</code>):</p>
  <pre><code>&gt;perl StringIndex.pl
  [1]: 0 &quot;abc&quot; [3] ()
  [2]: 1 &quot;abc&quot; [3] ()
  [3]: 2 &quot;abc&quot; [3] ()
  [4]: 3 &quot;abc&quot; [3] ()
  [5]: 3 &quot;abc&quot; [3] ()
  [6]: 3 &quot;abc&quot; [3] ()
  [7]: 3 &quot;abc&quot; [3] ()
  </code></pre>
  <p>However when encoding is involved, the return value changes. The return value changes as if the string being searched is not bounded by its length when called <strong>with</strong> <code>Encode::decode()</code> for ASCII characters &quot;abc&quot; (<code>$ARGV[0] = 1</code>):</p>
  <pre><code>&gt;perl StringIndex.pl 1
  [1]: 0 &quot;abc&quot; [3] ()
  [2]: 1 &quot;abc&quot; [3] ()
  [3]: 2 &quot;abc&quot; [3] ()
  [4]: 3 &quot;abc&quot; [3] ()
  [5]: 4 &quot;abc&quot; [3] ()
  [6]: 5 &quot;abc&quot; [3] ()
  [7]: 6 &quot;abc&quot; [3] ()
  </code></pre>
  <p>As a Side Note:</p>
  <ol>
  <li><code>substr</code> is set to empty string (&quot;&quot;) in above example, but in my real program it is a variable that changes value depending on condition.</li>
  <li>I understand the simplest solution is to check if <code>substr</code> is empty and not enter the <code>while</code> loop</li>
  <li>I am using &quot;This is perl 5, version 28, subversion 1 (v5.28.1) built
  for MSWin32-x64-multi-thread&quot;</li>
  </ol>