Confusing Postfix ,= Operator Behavior in Raku
In Raku, the postfix ,=
operator is a shorthand for the =
assignment operator followed by a comma (,
). This means that the expression:
foo ,= bar
is equivalent to:
foo = foo, bar
For example, the following code assigns the value 3
to the first element of the array @a
:
@a ,= 3
This is equivalent to the following code:
@a = @a, 3;
The Great List Refactor
In 2015, Raku underwent a major refactoring of its list handling capabilities. As a result of this refactor, the single argument rule became active everywhere. This means that the right-hand side of an expression must be a single argument. If the right-hand side is not a single argument, it will not be flattened.
In the case of the ,=
operator, this means that the @a
on the right-hand side of the expression will not be flattened. As a result, you will be creating a self-referential array, in which the first element refers to itself.
For example, the following code will output the message Self-referential array
:
my @a;
@a ,= @a;
say @a;
This is because the @a
on the right-hand side of the expression is not a single argument, so it is not flattened. As a result, the first element of the array @a
refers to itself.
Associative Arrays
For reasons that are not entirely clear, the single argument rule does not apply to objects that implement the Associative role. This means that in the case of associative arrays, the %a
on the right-hand side of the expression will be flattened. As a result, the given Pair
will be added to the hash.
For example, the following code will output the message {a => 11, b => 22, x => 33}
:
my %a = :11a, :22b;
%a = %a, :33x;
say %a;
This is because the %a
on the right-hand side of the expression is an associative array, so it is flattened. As a result, the given Pair
is added to the hash.
Conclusion
In the case of arrays, the ,=
operator is not very useful. Before the Great List Refactor, it may have done what you expected. However, it would have been inconsistent with other situations, and consistency was deemed more important.
Instead of using the ,=
operator, you can use the following array operations:
push
pop
shift
unshift