0

在下面的代码中,为什么第一个智能匹配失败并给出警告Argument "two" isn't numeric in smart match,而第二个智能匹配按预期工作(匹配)?

use strict;
use warnings;
use feature 'say';

my %h = ("one" => "un", "two" => "deux");
my $v = "two";
my @keys_h = keys %h;

say "matches first form"  if $v ~~ keys %h; # warning, doesn't match
say "matches second form" if $v ~~ @keys_h; # no warning, matches

我意识到我可以使用

$v ~~ %h

但我想知道为什么第一个 smartmatch 不能像我期望的那样工作。我正在使用 Perl 5.10.1。

4

1 回答 1

3

Because an array and a list are not the same thing.

$v ~~ @keys_h

is matching a scalar against an array, (Any vs Array in the smart match behavior chart) returning true if the scalar matches an element of the array.

$v ~~ keys %h

is matching a scalar against a list. There is no rule for matching against a list, so the list is evaluated in scalar context, like

$v ~~ scalar(keys %h)

which resolves to

"two" ~~ 2

which is now a numeric comparison (Any vs. Num), which triggers the warning.

$v ~~ [ keys %h ]

would do what you want it to do, too.

于 2013-08-14T23:02:08.207 回答