perl - 什么决定了 `split` 的标量/列表上下文?

标签 perl split

根据perlsecret ,goatse 运算符 =()= 提供了一个列表上下文,以便它可以计算其元素的数量。我曾经也这么认为。但是当我不小心将运算符与 split 一起使用时,我注意到一些奇怪的事情。

下面的前两行与Effective Perl 编程,第二版中编写的语句完全相同。但事实上,split 似乎改变了左侧的行为。

my $wc;
$wc = () = "foo:bar:buz" =~ m/(\w+)/g;  # => 3
$wc = () = split /:/, "foo:bar:buz";   # => 1

$wc = (undef) = split /:/, "foo:bar:buz";   # => 2
$wc = (undef, undef) = split /:/, "foo:bar:buz";   # => 3
$wc = (undef, undef, undef) = split /:/, "foo:bar:buz";   # => 3

有人能告诉我是什么导致了返回值的变化吗?

最佳答案

它记录在split中下面讨论 LIMIT:

when assigning to a list, if LIMIT is omitted (or zero), then LIMIT is treated as though it were one larger than the number of variables in the list;

这是一种优化,因此 Perl 不会创建值,然后立即丢弃。想象一下 $varX 而不是 undef

要避免这种优化,请指定限制为 -1:

$wc = () = split /:/, "foo:bar:buz", -1;

因为

If LIMIT is negative, it is treated as if it were instead arbitrarily large; as many fields as possible are produced.

关于perl - 什么决定了 `split` 的标量/列表上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59827008/

相关文章:

r - 在 R 中使用循环使用不同的数据集运行回归?

perl - 如何重新加载 'require' 调用的内容?

perl - 面向对象的 Perl 中的包、模块和类有什么区别?

mysql - 为什么 Perl 的 DBI 占位符会因负数 MySQL 查询而中断?

perl - Perl 中的右对齐数字

python - 尝试将一个大的 .pdf 拆分为多个文件。 ( python ,pdftk)

java - 没有 csv 的 split() 方法

perl - 使用 Perl 删除空行和空格

php - 将字符串转换为 JSON,通过 JQuery.Ajax 获取

c# - 删除早于今天日期的文件