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.


In reply to Re: Perl index() Function Returns String, Not Numeric by ikegami
in thread Perl index() Function Returns String, Not Numeric by ironmo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.