为什么针对键%h的smartmatch失败并给出“参数不是数字”警告? [英] Why does smartmatch against keys %h fail and give an "Argument isn't numeric" warning?

查看:140
本文介绍了为什么针对键%h的smartmatch失败并给出“参数不是数字”警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,为什么第一个smartmatch无法匹配并给出警告参数two在智能匹配中不是数字,而第二个smartmatch工作正常如预期的那样(匹配)?

In the following code, why does the first smartmatch fail to match and give the warning Argument "two" isn't numeric in smart match, while the second smartmatch works as expected (it matches)?

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

我知道我可以使用

I realize I could just use

$v ~~ %h

但我想知道为什么第一次smartmatch不能按照我预期的那样工作。我使用Perl 5.10.1。

but I'd like to know why the first smartmatch doesn't work as I expect it to. I'm using Perl 5.10.1.

推荐答案

因为数组和列表不是同一回事。

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

$v ~~ @keys_h

Any vs Array http://search.cpan.org/~rjbs/perl-5.18.1/pod/perlop.pod#Smartmatch_Operatorrel =nofollow>智能匹配行为图表)如果标量匹配元素,则返回true

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

现在是一个数字比较(任何 Num ),这会触发警告。

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

$v ~~ [ keys %h ]

也会做你想做的事。

这篇关于为什么针对键%h的smartmatch失败并给出“参数不是数字”警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆