develooper Front page | perl.perl6.users | Postings from December 2021

Re: Subscripting, semicolons, and adverbs

Thread Previous | Thread Next
From:
Ralph Mellor
Date:
December 11, 2021 19:28
Subject:
Re: Subscripting, semicolons, and adverbs
Message ID:
CAPLR5SeHu3vTUYBPV0nRX8zgTtn6CuTAV25E+XZt4byi_=6AdA@mail.gmail.com
TL;DR  Raku does not treat a negative index as valid. To specify the index
of the last element, write `*-1`. What you're seeing is Raku trying to inform
you that you are using invalid indices.

On Fri, Dec 10, 2021 at 9:49 PM Sean McAfee <eefacm@gmail.com> wrote:
>
> @array[-1]:exists is a syntax error, even though it looks like
> it should just evaluate to True.

In Raku `foo[-N]` is invalid. At compile-time if N is statically
known, otherwise at run-time.

You must be used to PLs that treat a negative index as an offset
from the end. Designers of older PLs considered this a feature.

And indeed, for *literal* values it's arguably a reasonable choice,
saving a character compared to Raku's alternative (`*-1`).

But a mass of empirical evidence has shown that when this
idiom is applied to *variables* it becomes a bug magnet. So
Raku avoided that mistake, and instead carefully treats any
negative indices as errors.

These errors are reported at compile-time if the indices are
literal, and at run-time if they're variables or expressions.

By default run-time errors are reported via `Failure`s that
are returned as the (error) value(s) of the failed indexing.

`Failure`s are wrapped `Exceptions` that serve as (error)
values. If you handle them, they are disarmed, but if you
don't, or try to use them as if they were non-error values,
they blow up at the first sensible time to do so. That is to
say, immediately if you try to use them when unhandled
or at their `DESTROY` time if you don't.

> Actually, I get a bunch of those errors, as if they were stored
> up by all my previous evaluations of @a[$i;$i]:exists.

Yes. They are stored up because you ignored them, or at
least didn't handle them. If you reread the error messages
you'll see that that's what they convey.

> If I continue to evaluate the expression repeatedly, I get
> a run of Falses, then another batch of errors at some later
> point.

Exactly as they should.

> I wonder if I'm somehow invoking undefined behavior

No. You're "just" getting errors, suitably reported given Raku's design.

--
love, raiph

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About