繁体   English   中英

perl分裂奇怪的行为

[英]perl split strange behavior

我提前道歉,这可能是一个非常愚蠢的问题,有一个显而易见的解决方案,它逃避了一个相当初学者的眼睛,或者它也可能已经在Stackoverflow中作为一个解决的问题,但我缺乏关于究竟是什么的知识寻找是阻止我实际找到答案。

我有一个字符串:

$s = FOO: < single blankspace> BAR <some whitespace character> some more text with     whitespace that can span over multiple lines, i.e. has \n in them ; 

#please excuse the lack of quotes, and large text describing the character in angular brackets, but in this example, but I have the string correctly defined, and in plase of <blankspace> I have the actual ASCII 32 character etc.

现在我想以这种方式拆分$ s:

($instType, $inst, $trailing) = split(/\s*/, $s, 3);
#please note that i do not use the my keyword as it is not in a subroutine
#but i tested with my, it does not change the behavior

我希望,$ instType取值FOO :,没有任何周围的空间,在实际的测试字符串中有一个冒号,我相信,据我所知,它将保留在$ instType中。 然后很明显地期望$ inst与BAR相似,没有任何周围的空间,然后最后一个人也可以依靠$ trail来获取其余的字符串。

但是,我得到:$ instType需要F,这只是单个字符,$ inst需要O,字符串$ trail中第二个位置的单个字符需要O:BAR和其余部分。

我该如何解决这个问题?

PS perl是5.18.0

问题是允许零空间(零或更多)的量词* ,你必须使用+代替,这意味着1或更多。

请注意,F和O之间的空间正好为零。

你写了:

#please note that i do not use the my keyword as it is not in a subroutine
#but i tested with my, it does not change the behavior

你也可以而且应该使用my的子程序之外的东西。 结合use strict使用它可以防止像这样的愚蠢错误:

$some_field = 'bar';
if ( $some_feild ) { ... }

如果这些陈述是分开的,那么追查那个bug可能非常困难。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM