index returns 0 for NULL substring

B

Bill

#!/usr/local/bin/perl
# try.pl

use strict;

my $string = 'ABC';
my $substr = '';
my $rval = index($string,$substr);

print "-> $rval\n";

__END__

$ try.pl
-> 0

Why does this happen? It seems that index() should return -1.

$ perldoc -f index
index STR,SUBSTR,POSITION
index STR,SUBSTR
The index function searches for one string within
another, but without the wildcard-like behavior of a
full regular-expression pattern match. It returns
the position of the first occurrence of SUBSTR in
STR at or after POSITION. If POSITION is omitted,
starts searching from the beginning of the string.
The return value is based at "0" (or whatever you've
set the "$[" variable to--but don't do that). If
the substring is not found, returns one less than
the base, ordinarily "-1".
 
B

Brian McCauley

my $string = 'ABC';
my $substr = '';
my $rval = index($string,$substr);
Why does this happen? It seems that index() should return -1.

Can you explain why you would expect that?

When you look for nothing you'll always find it immediately.

--
\\ ( )
. _\\__[oo
.__/ \\ /\@
. l___\\
# ll l\\
###LL LL\\
 
P

Paul Lalli

#!/usr/local/bin/perl
# try.pl

use strict;

my $string = 'ABC';
my $substr = '';
my $rval = index($string,$substr);

print "-> $rval\n";

__END__

$ try.pl
-> 0

Why does this happen? It seems that index() should return -1.

It happened because the null string IS found within that string. It's
found within every string. It's found before and after every character in
every string. It is therefore found at position 0, position 1, position
2, etc....

Basically, you're asking perl "What is the first location in which the
next 0 characters are equal to this string of 0 characters?" Obviously,
that will be vacuuously true at every position in the string.


Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,371
Latest member
Brkaa

Latest Threads

Top