4

I can construct a hash as follows with the hash constructor:

my $h={entry=>"hello"};

However if this is used at the end of a map statement, I get a list of pairs:

[^3].map({ {entry=>$_} }).say;
##Output:  (entry => 0 entry => 1 entry => 2)

I can fix this with a coercer to give me a list of hashes as I want:

[^3].map({ %(entry=>$_) }).say;
##Output: ({entry => 0} {entry => 1} {entry => 2})

I know the {} operator is overloaded with block creation, but I don't understand the returning of pairs instead of a Hash in this example. Could someone enlighten me on this? Are there other situations I would get a list of pairs instead of a hash using the 'hash' constructor? Thanks!

Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105
drclaw
  • 2,463
  • 9
  • 23
  • 2
    This is a duplicate of [Is that a Perl 6 Hash or Block?](https://stackoverflow.com/questions/44101411/is-that-a-perl-6-hash-or-block). `{ foo => 42 }` is a `Hash`. `{ foo => $_ }` is a `Block` that returns a `Pair`. "I know the `{}` operator is overloaded with block creation" [but] "Are there other situations I would get a list of pairs instead of a hash using the 'hash' constructor?" These sentences contradict each other. `{ ... }` is *not* "the 'hash' constructor". It constructs *either* a `Block` or a `Hash`. I think `%( ... )` is unambiguously **a** 'hash' constructor in `6.d`. – raiph Sep 15 '19 at 09:18
  • 3
    To be clear, it's got nothing to do with `map`. Thus, eg, `my $h={entry=>$_}; say WHAT $h; # (Block)`. – raiph Sep 15 '19 at 10:20
  • 2
    @raiph Thanks for the pointer to the other question. I overlooked the `$_` variable... makes more sense now. – drclaw Sep 15 '19 at 10:36

0 Answers0