Search code examples
arrayspointersclonevariable-assignmentraku

perl6 array assignment: pointer or copy?


In perl6, I want to assign an array to another array and have the resulting array be distinct entity, but it seems neither direct assignment nor cloning can do what I want. Is there a way to copy array over with one expression instead of writing a loop routine?

To exit type 'exit' or '^D'
> my @a=<a b c d e>
[a b c d e]
> my @b = <1 2 3 4 5 6 7>
[1 2 3 4 5 6 7]
> my @c = @a
[a b c d e]
> @c[3]
d
> @c[3]=3;
3
> @c
[a b c 3 e]
> @a
[a b c d e]
> @c === @a
False
> @c == @a
True          # this is unexpected, @c and @a should be different, right?
> my @[email protected]
[a b c d e]
> @x[3]=3
3
> @x
[a b c 3 e]
> @x === @a
False
> @x == @a
True         # unexpected, @x and @a should be distinct things, right?
>

Solution

  • You were unlucky to not compare with @b that might have helped you figure it out :)

    == is numeric comparison, so when you asked for a list to be compared as a number it picked the number of elements as a representation. Operators in Perl 5 or 6 coerce the types involved. If you want to test if the elements of the array are the same try the eqv operator.

    Comparing lengths of arrays, so the following is true:

    @a == @c == @x == 5
    

    Try:

    my @a = <a b c d e>;
    my @b = <1 2 3 4 5>;
    @a eqv @b;
    

    You might want to check out some of the docs around these operators. The smart match ~~ operator is probably more what you were expecting with ==.

    https://docs.perl6.org/routine/$EQUALS_SIGN$EQUALS_SIGN https://docs.perl6.org/routine/$TILDE$TILDE