2013-12-22 50 views
6

我很抱歉,這可能是一個非常愚蠢的問題,有一個明顯的解決方案,它在perl中逃避了一個相當初學者的眼睛,或者它也可能在Stackoverflow中作爲一個已解決的問題,但是我的缺乏關於究竟要尋找什麼的知識阻止我實際找到答案。perl分裂奇怪的行爲

我有這樣的字符串:

$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採取男,這僅僅是單個字符, $研究所需要O,在串 $線索的第2位的單字節字符需要O:BAR和休息。

我該如何解決這個問題?

PS Perl是5.18.0

+0

你讓'\ s *'爲可選的,所以只要可以,它什麼都不匹配。 – sln

回答

12

問題是量詞*允許零空間(零個或多個),則必須使用代替+,這意味着1個或多個。

注意,有F和O.

+0

呃非常感謝你。它讓我等4分鐘,直到接受 – Sean

+0

@ Sean:fröhlicheWeihnachten! –

+0

aw,danke sehr,euch auch! – Sean

1

之間恰好爲零空間時寫道:

#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。