[英]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.