in reply to Perl index() Function Returns String, Not Numeric
index doesn't return true/false because we need to distinguish the result of index('abcde', 'xyz') from the result of index('abcde', 'abc'). The language designer(s) chose to use -1 (well, $[ - 1) to signal "no match". The return value is documented. undef might have been a better choice, but it still wouldn't allow the syntax you attempted to use.
If you wish to use index in the if expression, you can do the following:
if ((my $index = index $string, $key) >= 0) { ... }
Believe it or not, you actually have to force a numeric context to get it to work:
>= 0 doesn't just force numerical context. It also check if the number is positive. 0+$index would force numerical context, but it doesn't help here because index doesn't care about context. index always returns a number.
use Devel::Peek qw( Dump ); Dump(index('abcdef', 'abc')); # IOK ==> number Dump(index('abcdef', 'xyz')); # IOK ==> number
Unlike pretty much any other function that returns 'false' in Perl, meaning 0 or a negative number or undef
Negative is never considered false. Perl considers the following (and only the following) false: Zero (0, 0EO, etc), the string consisting of just the character zero ("0"), the empty string (""), the undefined value (undef) and things which evaluate to that listed when in scalar context.
Update: Tweaks throughout.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl index() Function Returns String, Not Numeric
by tilly (Archbishop) on Aug 19, 2006 at 07:49 UTC |