什么是"~~ "在 Perl 中是什么意思? [英] What does " ~~ " mean in Perl?

查看:80
本文介绍了什么是"~~ "在 Perl 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SO 答案 daxim 声明:

<块引用>

@array ~~ $scalar 当 $scalar 在 @array 中时为真

draegtun 回复的内容:

<块引用>

从 5.10.1+ 开始,~~的顺序是重要的.因此它需要是 $scalar~~ @数组

关于~~ 的小入门书如何,其中包含指向源代码的链接,包括以下具体问题:什么是~~?~~ 叫什么?为什么顺序在一个版本中很重要,而在前一个版本中不重要?

请注意,一个好的摘要可能无法获得所有详细信息,并且可能难以编写.介绍或入门对于不熟悉~~的人来说非常有用,同时可以扩大此Perlism的曝光率.

搜索字符串: non-word-tilde-tilde non-word-at-sign.

解决方案

专门回答为什么顺序在一个版本中很重要而在前一个版本中不重要":5.10.0 中的智能匹配运算符在某种程度上设计得很糟糕这使得它难以可靠地使用,并且使 given/when 构造变得不那么有用,因此语义在 5.10.1 中发生了变化,所有未来的版本都将假装 5.10.0 版本从未存在过.

在 5.10.1+ 版本的智能匹配中,~~ 的左操作数和右操作数总是被区别对待.就像 =~ 正则表达式匹配运算符一样,左侧是匹配的主题",右侧是匹配的模式"——无论是纯标量,一个正则表达式、一个数组或散列引用、一个代码引用或其他任何东西.perlsyn 中详细说明了细节.

您完全不必担心 5.10.0 版本,除非您已经编写了依赖于 5.10.0 语义的代码(在这种情况下,您应该将其重写为 require 5.10.1,否则它将打破所有未来版本的 perl).

In an SO answer daxim states:

@array ~~ $scalar is true when $scalar is in @array

to which draegtun replies:

From 5.10.1+ the order of ~~ is important. Thus it needs to be $scalar ~~ @array

How about a small primer on ~~ with link(s) to source(s) including the following specific questions: What is ~~? What is ~~ called? Why does the order matter in one version but not in a previous one?

Note that a good summary may not get all the details and can be hard to write. An introduction or primer would be very useful to save time for someone unfamiliar with ~~ while expanding the exposure of this Perlism.

Search strings: non-word-tilde-tilde non-word-at-sign.

解决方案

Answering specifically "why does the order matter in one version but not in a previous one": the smart match operator was badly designed in 5.10.0 in a way that made it difficult to use reliably, and made the given/when construct less useful than it could be, so the semantics were changed with 5.10.1 and all future versions will pretend that the 5.10.0 version never existed.

In the 5.10.1+ version of smart match, the left operand and the right operand to ~~ are always treated distinctly. Just as with the =~ regex match operator, the left side is the "subject" of the match, and the right side is the "pattern" to match against -- whether that be a plain scalar, a regex, an array or hash reference, a code reference, or whatever. The specifics are detailed pretty well in perlsyn.

You shouldn't worry about the 5.10.0 version at all unless you've already written code that depends on the 5.10.0 semantics (in which case, you should rewrite it to require 5.10.1, or else it will break on all future versions of perl).

这篇关于什么是"~~ &quot;在 Perl 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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