index()函数第三个参数的错误提示是否存在错误?
index() function incorrect? Let's break this down clearly:
First, let's nail down why your code is throwing an error in the first place:
- You declared
my $foo;without assigning an initial value, so it starts as an undefinedAnytype (not the 0 you expected). - When you first call
index $word, "a", $foo, you're passing an undefined value as the third$posargument. Raku'sindexfunction requires this position argument to be a definedCooltype (marked asCool:Din the signature), which your uninitialized$fooisn't.
Now, about the error message itself:
The core of the error message is accurate—it correctly flags that your call index(Str: Str, Any) doesn't match any valid signature for the function. The first three listed signatures are complete and correct:
(Str:D $: Cool:D $needle, *%_): Call with just a search needle (no starting position)(Str:D $: Str:D $needle, *%_): Same as above, but explicitly for string needles(Str:D $: Cool:D $needle, Cool:D $pos, *%_): Call with a needle plus a defined starting position
The only issue is the fourth signature in the list: (Str:D $: Str:D $needle, ... — this is truncated. It should fully display the signature for a string needle plus a defined position, like (Str:D $: Str:D $needle, Cool:D $pos, *%_). That truncation is a minor formatting flaw in the error message, but it doesn't undermine the correct core diagnosis: your uninitialized variable doesn't meet the type requirements for index's third argument.
To fix your code, just initialize $foo to 0 instead of leaving it undefined:
sub count-a { my $word = "banana"; my $count = 0; my $foo = 0; # Initialize to the starting position you intended while True { $foo = index $word, "a", $foo; last unless $foo.defined; $foo++; $count++ } return $count; } say count-a; # Outputs 3, the correct number of "a"s in "banana"
内容的提问来源于stack exchange,提问作者Clint

