【问题标题】:perl split strange behaviorperl拆分奇怪的行为
【发布时间】:2014-01-11 01:15:53
【问题描述】:

我提前道歉,这可能是一个非常愚蠢的问题,它有一个明显的解决方案,它在 perl 中逃避了一个相当初学者的眼睛,或者它也可能在 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

【问题讨论】:

  • 您将\s* 设为可选,因此它尽可能不匹配任何内容。

标签: regex perl split


【解决方案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 ) { ... }

如果将这些语句分开,则可能很难找到该错误。

【讨论】:

    【解决方案2】:

    问题是量词* 允许零空间(零或更多),您必须改用+,这意味着1 或更多。

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

    【讨论】:

    • 嗯,非常感谢。它要求我等待 4 分钟直到接受
    • @Sean: fröhliche Weihnachten!
    • 哎呀,danke sehr,哎呀!
    猜你喜欢
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    相关资源
    最近更新 更多