[% setvar title rindex and index should return true/false values %]

This file is part of the Perl 6 Archive

Note: these documents may be out of date. Do not use as reference!

To see what is currently happening visit http://www.perl6.org/

TITLE

rindex and index should return true/false values

VERSION

  Maintainer: Nathan Torkington <gnat@frii.com>
  Date: 12 Sep 2000
  Last Modified: 15 Sep 2000
  Mailing List: perl6-language@perl.org
  Number: 213
  Version: 2
  Status: Developing

ABSTRACT

index() and rindex() should return undef if their second argument is not a substring of their first argument. If the substring occurs at the start of the first argument, they should return "0 but true".

CHANGES

 * added "0 but true" suggestion

DESCRIPTION

In perl5, index() and rindex() return -1 if the substring isn't found. This seems out of step with the rest of Perl's functions, which return undef on error. I propose changing index() and rindex() to return undef if the substring isn't found.

This would also cause warnings to be issued when programmers use the results of index() or rindex() assuming the substring was found.

This suggestion doesn't rely on RFC 53, "Built-ins: Merge and generalize index and rindex", and works regardless of whether 53 is accepted or not.

When the substring occurs at the start of the larger string, the functions should return "0 but true". This is exempt from "isn't numeric" warnings, and gives them useful boolean return values:

  if (index($big_string, $little_string)) {
    print "$little_string is in $big_string";
  }

without breaking their existing numeric uses.

IMPLEMENTATION

The perl526 translator could turn index($a,$b) calls into

  do { my $tmp = index($a,$b);
       if (defined($tmp)) { 0 + $tmp }
       else               { -1       }
  }

REFERENCES

RFC 53: Built-ins: Merge and generalize index and rindex

perlfunc manpage for information on index() and rindex()