I have created a very small sample code below to illustrate how Perl's index() function's return value changes for empty substr ("") on string that is passed or not passed through Encode::decode().
use strict;
use Encode;
my $mainString = (@ARGV >= 2) ? $ARGV[1] : "abc";
my $subString = (@ARGV >= 3) ? $ARGV[2] : "";
if (@ARGV >= 1) {
$mainString = Encode::decode("utf8", $mainString);
}
my $position = index($mainString, $subString, 0);
my $loopCount = 0;
my $stopLoop = 7; # It goes for ever so set a stopping value
while ($position >= 0) {
if ($loopCount >= $stopLoop) {
last;
}
$loopCount++;
print "[$loopCount]: $position \"$mainString\" [".length($mainString)."] ($subString)\n";
$position = index($mainString, $subString, $position + 1);
}
Before getting into with vs without Encode::decode(), what should the return value of index() be for an empty substr ("") because Perl's documentation does not mention it. Although it does not mention it, here is the execution result without calling Encode::decode() for ASCII characters "abc" (@ARGV = 0):
>perl StringIndex.pl
[1]: 0 "abc" [3] ()
[2]: 1 "abc" [3] ()
[3]: 2 "abc" [3] ()
[4]: 3 "abc" [3] ()
[5]: 3 "abc" [3] ()
[6]: 3 "abc" [3] ()
[7]: 3 "abc" [3] ()
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 with Encode::decode() for ASCII characters "abc" ($ARGV[0] = 1):
>perl StringIndex.pl 1
[1]: 0 "abc" [3] ()
[2]: 1 "abc" [3] ()
[3]: 2 "abc" [3] ()
[4]: 3 "abc" [3] ()
[5]: 4 "abc" [3] ()
[6]: 5 "abc" [3] ()
[7]: 6 "abc" [3] ()
As a Side Note:
substris set to empty string ("") in above example, but in my real program it is a variable that changes value depending on condition.- I understand the simplest solution is to check if
substris empty and not enter thewhileloop - I am using "This is perl 5, version 28, subversion 1 (v5.28.1) built for MSWin32-x64-multi-thread"