What is the syntax for deleting an array element if you don't know its index?

Depends on what you call delete. Internally, on arrays, doing a DELETE-POS binds the element in the array to nqp::null, which will discard any container living at that position. At the HLL level, this is represented by the type of the array:

my Str @letters = <a b c>;
@letters[1]:delete;
say @letters;   # [a (Str) c]

However you can achieve the same effect by assigning Nil:

my Str @letters = <a b c>;
@letters[1] = Nil;
say @letters;   # [a (Str) c]

In this case, the container at that element stays the same, you just let it revert to its "natural" state. And if you're content with that type of deletion, you can also use that in your loop:

my Str @letters = <a b c>;
$_ = Nil if $_ eq "b" for @letters;
say @letters;   # [a (Str) c]

When I said: revert to its natural state, this also includes any default value:

my Str @letters is default<foo> = <a b c>;
$_ = Nil if $_ eq "b" for @letters;
say @letters;   # [a foo c]

If you want to really eradicate the elements from the list without keeping the existing elements at their positions, you can of course use grep:

my @letters = <a b c>;
@letters .= grep: * ne "b";
say @letters;  # [a c]

But that does not seem like what you intended.


Please read Lizmat's answer for thoughtful and helpful analysis of your titular question in which she pays appropriate attention to the ambiguity of the English word "deleting".

Here's one way to massage one of the suggestions in her answer back into use of the :delete adverb so that the final @letters remains the same array with the first element :delete'd so the result is the same as your original ([(Any) b c]):

my @letters = <a b c>;
.[.grep: 'a', :k]:delete given @letters;
say @letters;

The :k adverb on the grep tells it you want the result to be the index.

Tags:

Arrays

Raku