加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

数组 – 使用split(//,$str,$limit)返回尾随的空元素,矛盾的文档

发布时间:2020-12-15 22:00:23 所属栏目:大数据 来源:网络整理
导读:我试图将一个字符串拆分成它的组件字符. 为此,我一直按照 the documentation的建议使用split(//,$str): However,this: print join(':',split(//,'abc')),"n"; uses empty string matches as separators to produce the output a:b:c ; thus,the empty stri
我试图将一个字符串拆分成它的组件字符.
为此,我一直按照 the documentation的建议使用split(//,$str):

However,this:
print join(':',split(//,'abc')),"n";
uses empty string matches as separators to produce the output a:b:c ; thus,the empty string may be used to split EXPR into a list of its component characters.

在我的脚本中,我需要一个前N个字符的数组或第一个长度($str) – 1个字符,取较小者.为了达到这个目的,我使用split(//,$str,$n 1)并丢弃最后一个元素.

在理论上这应该是正常的.如果LIMIT小于字符串长度,则所有额外的字符被分组到被丢弃的最后一个元素中.如果LIMIT大于字符串长度,则最后一个元素是被丢弃的最后一个字符.

这是我遇到的一个问题.

文件说:

…and each of these:
print join(':','abc',3)),"n";
print join(':',4)),"n";
produces the output a:b:c.

但这不是我得到的结果.如果LIMIT大于字符数,则结果数组始终以恰好一个空白元素(demo)结尾:

print join(':',1)),"n";    # abc
print join(':',2)),"n";    # a:bc
print join(':',"n";    # a:b:c
print join(':',"n";    # a:b:c:
print join(':',99)),"n";    # a:b:c:

这些结果与文档中的示例直接相矛盾.

文件是否出错?我的Perl版本(v5.22.2)是错的吗?
如果这种行为是无法避免的,我该如何才能完成我的原始目标?

解决方法

看来文档中的示例不正确.以下文档进一步下降:

An empty trailing field,on the other hand,is produced when there is a match at the end of EXPR,regardless of the length of the match (of course,unless a non-zero LIMIT is given explicitly,such fields are removed,as in the last example).

因为我提供的是非零LIMIT,所以保留尾随的空字段.空模式//在最后一个字符之后但在字符串结束之前匹配,因此产生一个尾随的空字段.

评论中提出的解决方法 – 使用(?!$)的拆分模式或使用substr($str,$n)作为输入 – 都可以正常工作.但是,我并不是强制拆分合作,而是选择将pop(@arr)中的“放弃最终元素”逻辑更新为(@arr&& pop(@arr)eq“”){}.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读