Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I see odd behavior of subscript on scalars?

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.

like image 250
Chas. Owens Avatar asked Dec 14 '22 03:12

Chas. Owens


1 Answers

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 class List, and coerce to List 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.

like image 194
Christoph Avatar answered Jan 03 '23 01:01

Christoph