in reply to Split unless contained by

Starting from the premise that a lame but almost working answer is better than none:

/( #A nice simple capture, for [^|\{]+ #a block of nonsignificant chars | \{ [^}]+ \} #or a bracketed block ) \| #followed by a pipe. /x

Doesn't _quite_ work - produces the following on output:

$VAR1 = [ '', 'foo', '', '{baz|qux}', 'fax' ];

This indicates my need for enlightenment - if I use (?:) instead of (), it returns just (' ',' ','fax'), not the captures... so maybe there's some deeper magic going on in split which I'm not clear on.

Update: Found why it's adding the captured elems, but not why using (?:) breaks it.

from split manpage:

If the PATTERN contains parentheses, additional list elements are crea +ted from each matching substring in the delimiter.

Update again: Now I fool feelish. Okay, yup, like would make sense, split uses pre/postmatch stuff - the end result being that since (?:) is part of the match, it gets dropped, and since that's the content I'm looking for (the foo or {bar|baz} bit), I lose my content.

hm. now I'm as stumped as BUU. Can't use lookbehinds, cuz variable length lookbehinds aren't implemented... *falls into contemplative silence*.

But is that approximately what you're looking for?

Replies are listed 'Best First'.
Re: Re: Split unless contained by
by belkajm (Beadle) on Aug 09, 2002 at 23:31 UTC
    if you modify this slightly, and use it in this form it seems to work:
    $a = "foo|{baz|qux}|fax"; @b = ($a =~ /( [^|\{]+ | \{ [^}]+ \} ) (?: \| | $ ) /xg);
    @b now contains:
    $VAR1 = [ 'foo', '{baz|qux}', 'fax' ];
    Note that this regexp can't cope with recursive brackets, and can therefore be fooled. Any example of this would be:
    $a = "foo|{baz|{qu}x|fax";
    which would result in:
    $VAR1 = [ 'foo', 'baz', 'qu}x}', 'fax' ];

    I'm afraid that I haven't got round to getting the owl book yet, so i'm not really that hot with regexps yet. In fact, i'm coming back to perl now from a years absence. If someone could show how to modify the regexp to cope with things like this, I would be grateful.

    Yoda