gpt4 book ai didi

perl - "evaluated directly for a Boolean result, and no smartmatching occurs"中的 "Programming Perl"是什么意思?

转载 作者:行者123 更新时间:2023-12-01 06:56:34 24 4
gpt4 key购买 nike

在“Programming Perl”一书中有一个片段(剪切):

By default, when(EXPR) is treated as an implicit smartmatch of $_; that is, $_ ~~ EXPR. However, if the EXPR argument to when is one of the 10 exceptional forms listed below, it is evaluated directly for a Boolean result, and no smartmatching occurs:

  1. ...

  2. A regular expression match in the form of /REGEX/, $foo =~ /REGEX/, or $foo =~ EXPR.



什么意思 evaluated directly for a Boolean result ?

例子:
#!/usr/bin/perl
use v5.14;
my @a = ('aaa', 'bbb', 'ccc');

given(@a) {
when (/a/) { say '@a contains an a'; }
default { say '@a does not contain an a' }
}

当我运行它时,输出会不时变化:
@a does not contain an a

@a contains an a

@a does not contain an a

@a does not contain an a

我不明白这里发生了什么,有人能乐于助人吗?

提前欣赏。

最佳答案

仔细阅读文档:

Another useful shortcut is that, if you use a literal array or hash as the argument to "given", it is turned into a reference. So "given(@foo)" is the same as "given(\@foo)", for example.



因此, given (@a)变成了 given(\@a) .没有智能匹配,因为你用的是 when (/a/) ,所以你试图匹配
\@a =~ /a/

引用是字符串化的。它有时包含“a”,如 ARRAY(0x9a4e7f8) ,但通常不会:-)

关于perl - "evaluated directly for a Boolean result, and no smartmatching occurs"中的 "Programming Perl"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11687349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com