In Python, if you index the structure of a collection with a capital key / index, you get a slap in the face:
>>> [1, 2, 3][9] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
This is an exception; this comes from BaseException, and if you can't handle it, my program will crash, which will almost always be what I want .
Perl 5 and 6 indexing a list does not seem to care about indexing outside:
$ perl6 > my @l = (1..4); [1 2 3 4] > say @l[2]; 3 > say @l[9]; (Any) > print @l[9]; Use of uninitialized value @l of type Any in string context <snip> True > my $x = @l[9];
this is basically the same in Perl 5, except that you will not get the return value, but execution continues as usual.
I do not understand why access outside of access should be without . The only warnings you receive are that this value can be “uninitialized” (but we all know that it really means nonexistent ) when you pass it to certain functions.
Can i fix this? I could implement my own post-circumfix indexing operator to override the default value that dies from the spam index, but there is no way to tell the difference between the uninitialized value and the type Any . The only way to do what I see is to check if the requested index is in the range List.elems() .
What is a (preferably minimal, simple, clean, readable, etc.) solution that I can use to fix this?
Before someone says yes, but the variable is not initialized, for example my $x; ! ": in C, you get segfault if you get access to memory that you didn't allocate; why can't I have that kind of security?
I noted this as Perl and Perl 6, because although I am studying Perl 6, and the features of this question apply mainly to 6, the main idea seems to be a general aspect of both 5 and 6.