Perl 在分隔符之前/之后用空文本分割 [英] Perl split with empty text before/after delimiters

查看:58
本文介绍了Perl 在分隔符之前/之后用空文本分割的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 Perl 的 split 命令有一些奇怪的行为,特别是在我希望结果数组包含空字符串 '' 但实际上没有的情况下.

I was noticing some curious behavior with Perl's split command, particularly in cases when I would expect the resulting array to contain empty strings '', but it actually doesn't.

例如,如果我在字符串的末尾(或开头)有一个分隔符,则生成的数组不会将空字符串 '' 作为最后一个(或第一个)元素.

For example, if I have a delimiter(s) at the end (or the beginning) of the string , the resulting array does not have an empty string(s) '' as the last (or first) element.

示例:

@s = split(/x/, 'axb')

产生 2 个元素的数组 ['a','b']

produces 2 element array ['a','b']

@s = split(/x/, 'axbx')

产生相同的数组

@s = split(/x/, 'axbxxxx')

产生相同的数组

但是一旦我把一些东西放在最后,所有这些空字符串都会作为元素出现:

But as soon as I put something at the end, all those empty strings do appear as elements:

@s = split(/x/, 'axbxxxxc')

产生一个 6 个元素的数组 ['a','b','','','','c']

produces a 6 element array ['a','b','','','','c']

如果分隔符位于开头,则行为类似.

Behavior is similar if the delimiters are at the beginning.

我希望分隔符之间、之前或之后的空文本始终在拆分中生成元素.任何人都可以向我解释为什么在 Perl 中拆分的行为是这样的?我刚刚在 Python 中尝试了同样的事情,它按预期工作.

I would expect empty text between, before, or after delimiters to always produce elements in the split. Can anyone explain to me why the split behaves like this in Perl? I just tried the same thing in Python and it worked as expected.

注意:Perl v5.8

Note: Perl v5.8

推荐答案

来自 文档:

默认情况下,保留空的前导字段,删除空的尾随字段.(如果所有字段都为空,则它们被视为尾随.)

By default, empty leading fields are preserved, and empty trailing ones are deleted. (If all fields are empty, they are considered to be trailing.)

这解释了您在尾随字段中看到的行为.这通常是有道理的,因为例如,人们通常对尾随空格非常粗心.但是,您可以根据需要获取尾随空白字段:

That explains the behavior you're seeing with trailing fields. This generally makes sense, since people are often very careless about trailing whitespace, for example. However, you can get the trailing blank fields if you want:

split/PATTERN/,EXPR,LIMIT

如果 LIMIT 为负,则将其视为已指定任意大的 LIMIT.

If LIMIT is negative, it is treated as if an arbitrarily large LIMIT had been specified.

所以要获取所有尾随空字段:

So to get all trailing empty fields:

@s = split(/x/, 'axbxxxxc', -1);

(我假设您在查看前导空字段时犯了一个粗心的错误 - 它们肯定会被保留.尝试 split(/x/, 'xaxbxxxx').结果大小为 3.)

(I'm assuming you made a careless mistake when looking at leading empty fields - they definitely are preserved. Try split(/x/, 'xaxbxxxx'). The result has size 3.)

这篇关于Perl 在分隔符之前/之后用空文本分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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