The [1,2]
inside the %h{[1,2]} = [3,4]
is interpreted as a slice. So it tries to assign %h{1}
and %{2}
. And since the key must be an Array
, that does not typecheck well. Which is what the error message is telling you.
If you itemize the array, it "does" work:
my %h{Array};
%h{ $[1,2] } = [3,4];
say %h.perl; # (my Any %{Array} = ([1, 2]) => $[3, 4])
However, that probably does not get what you want, because:
say %h{ $[1,2] }; # (Any)
That's because object hashes use the value of the .WHICH
method as the key in the underlying array.
say [1,2].WHICH; say [1,2].WHICH;
# Array|140324137953800
# Array|140324137962312
Note that the .WHICH
values for those seemingly identical arrays are different.
That's because Array
s are mutable. As List
s can be, so that's not really going to work.
So what are you trying to achieve? If the order of the values in the array is not important, you can probably use Set
s as keys:
say [1,2].Set.WHICH; say [1,2].Set.WHICH
# Set|AEA2F4CA275C3FE01D5709F416F895F283302FA2
# Set|AEA2F4CA275C3FE01D5709F416F895F283302FA2
Note that these two .WHICH
es are the same. So you could maybe write this as:
my %h{Set};
dd %h{ (1,2).Set } = (3,4); # $(3, 4)
dd %h; # (my Any %{Set} = ((2,1).Set) => $(3, 4))
Hope this clarifies things. More info at: https://docs.raku.org/routine/WHICH
%h{[1,2]} = [3,4];
to%h{item [1,2]} = [3,4];
it prevents the Array from being expanded into a slice and keeps it as an Array so it can be used as a key. – callyalater Apr 26 '18 at 21:04Set([1,2])
or~[1, 2]
meets my needs perfectly..perl
seems interesting but I am not sure how often I will use it practically during normal development. – Hunter McMillen Apr 30 '18 at 1:00~
, but as you presumably know I evolved my answer from a~
prefix to a.perl
postfix. That's because, afaik, other than brevity, it's at least as good as, and in many scenarios better than the other two hacks, namely regular stringification (~
) or.Set
per Liz's suggestion..perl
distinguishes[1,2]
and[2,1]
, which.Set
does not and distinguishes<<'a a' 'b'>>
and<<'a' 'a b'>>
which regular stringification (with~
) does not. Anyhoo, as you say,~
will work fine if all your array/list elements are integers. – raiph Apr 30 '18 at 6:22