Using the Perl 6 REPL:
> Map.new: 'A' => 1, 'B' => 2;
Map.new((:A(1),:B(2)))
> Map.new: A => 1, B =>2;
Map.new(())
I previously thought that A => 1
and 'A' => 1
would be identical because =>
is supposed to autoquote the word to its left, but in the second example the pairs seem to disappear.
Disclaimer: This tripped me up earlier today, so I'm posting it as Q&A in case it is helpful to someone else too. Also feel free to add your own answers.
In general, A => 1
and 'A' => 1
create equivalent Pair objects. But inside a subroutine or method call, the first syntax is parsed as named arguments instead of as a Pair. And in methods, unused named arguments are ignored, which explains the empty Map
created in your second statement. So, you have to take a little extra care that the parser does not interpret your pairs as named arguments. The following are all distinguishable from named arguments:
Map.new: (A=>1, B=>2); # extra set of parentheses
Map.new: 'A'=>1, 'B'=>2; # quote the keys
Map.new: 'A', 1, 'B', 2; # Don't use fat commas `=>`
By the way, this also demonstrates another reason to use the colon :
instead of ()
for method calls. Using parentheses may not be as clean:
Map.new( A=>1, B=>2); # oops, named arguments
Map.new((A=>1, B=>2)); # extra set of parentheses solves the issue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With