Perl 6 index

[email protected] (Aaron Sherman) 18 Sep 2002 01:46:39 -0400
Newsgroups perl.perl6.stdlib
Message-ID <1032328020.15243.240.camel@put>
Something that has long bothered me in C and Perl is the return from
index. -1 is such a non-answer to me.

In Perl 6, I was wondering if it would make sense for functions that
return a count or index to set the truth property as well. For example,
allowing:

	if index($subject,"**SPAM**") {
		warn "SpamAssassin doesn't like you :)";
	}

There are a lot of functions that do what index does or which return a
success count for list of actions (e.g. unlink or chmod). Should all of
these break with Perl 5's notion of boolean success and use Perl 6's
model?

Here's a sample of some of those:

    # Slow matching for example purposes
    sub index($string, $substr, int $pos //= 0) {
    	my int $subl = length($substr);
    	my int $strl = length($string);
    	for(int $i = $pos; $i+$subl <= $strl; $i++) {
    		return $i but true if substr($string,$i,$subl) eq $substr;
    	}
    	return -1 but false;
    }
    sub all_or_false(&code, @items) {
    	my $ok = 0;
    	for @items -> $_ {
    		$ok++ if code($_);
    	}
    	if $ok == @items {
    		return $ok but true;
    	} else {
    		return $ok but false;
    	}
    }
    sub chmod(int $mode, *@paths){
    	return all_or_false {syschmod($_,$mode)} @paths;
    }
    # ... also do chown, utime, kill, utime and unlink this way

-- 
Aaron Sherman <[email protected]>
http://www.ajs.com/~ajs