toapole has asked for the wisdom of the Perl Monks concerning the following question:

Hello
Why this code works:
my @test = ( {id => 1}, {id => 2} );
my @arr = map $_->{id}, @test;
say 1 ~~ @arr;
and this doesn't (namely context in matching is scalar):
my @test = ( {id => 1}, {id => 2} );
say 1 ~~ map $_->{id}, @test;
?
or i'm just in state of sin? :)

Replies are listed 'Best First'.
Re: map and smart match
by ikegami (Patriarch) on Jul 09, 2009 at 22:41 UTC
    Because map $_->{id}, @test is not an array. say 1 ~~ @{[ map $_->{id}, @test ]}; should do the trick. I wonder if say 1 ~~ [ map $_->{id}, @test ]; also works.

      The passage I bolded from what is to be 5.10.1's perlsyn answers my own question:

      The behaviour of a smart match depends on what type of thing its arguments are. The behaviour is determined by the following table: the first row that applies determines the match behaviour (which is thus mostly determined by the type of the right operand). Note that the smart match implicitly dereferences any non-blessed hash or array ref, so the "Hash" and "Array" entries apply in those cases. (For blessed references, the "Object" entries apply.)

Re: map and smart match
by JavaFan (Canon) on Jul 10, 2009 at 10:57 UTC
    Because in
    say 1 ~~ map $_->{id}, @test;
    the right hand side is first evaluated (in scalar context), yielding 2. And 1 ~~ 2 is false.