It appears as if a scalar by itself is sort of a list of one item:
> "foo"[1]
Index out of range. Is: 1, should be in 0..0
in block <unit> at <unknown file> line 5
> "foo"[0]
foo
> "foo"[*-1]
foo
I say sort of a list of one because lists don't seem to have a range on their indexes:
> (0, 1, 2)[3]
Nil
What is going on here. What am I not understanding about the []
operator.
This is a feature of Any
. From the docs:
Since Perl 6 intentionally confuses items and single-element lists, most methods in
Any
are also present on classList
, and coerce toList
or a list-like type.
If you look at the implementation, you'll see that there is no actual coercion necessary as Any
provides AT-POS
, and that's what fails for indices different from 0.
In contrast, the implementation of actual lists only fails in case of negative indices and returns Nil
otherwise.
Semantically, this is not entirely insane as one way to think of Nil
is as a quiet failure, but it is indeed an inconsistency. It might be by design, as the 'listiness' of items is just a convenience feature and not part of the interface proper and thus might be supposed to complain noisily if misused.
Note that Array
gives a third behaviour by returning Any
by default, which can be understood in the context of auto-vivification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With