Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi folks,

I have data with three delimiters, call them : % and ; The data look like this: xyz:yy;zz%foo:bar

I would like to split each line a la:

split /:|%|;/

But I would also like to obtain the delimiter, so that I have two arrays, the data, xyz,yy,zz,foo,bar and the delimiters :,;,%,:

Thanks for any suggestions!

Replies are listed 'Best First'.
Re: Split at multiple delimiters and get the delimiter
by kennethk (Abbot) on Mar 01, 2011 at 21:27 UTC
    As it states in split,
    If the PATTERN contains parentheses, additional list elements are created from each matching substring in the delimiter.
    You can therefore get your desired result with split /(:|%|;)/, where your result list will alternate data and delimiter. If you really want to split it into two arrays, you could do something like:
    my @values; my @delims; for (split /(:|%|;)/) { if (@values == @delims) { push @values, $_; } else { push @delims, $_; } }
Re: Split at multiple delimiters and get the delimiter
by jeffa (Bishop) on Mar 01, 2011 at 21:27 UTC

    Just add parens:

    split /(:|%|;)/
    and the delimiters will be captured ... but why put them in another array? Surely you won't be able to line them back up again ...

    Update: regardless of why, you could do something like so:

    /\W/ ? push @a,$_ : push @b,$_ for split /(:|%|;)/
    Where @a would contain the delimiters and @b contains the data ...

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Split at multiple delimiters and get the delimiter
by eff_i_g (Curate) on Mar 01, 2011 at 21:32 UTC
    Your question has been answered; however, I suggest using a character class rather than alternating single characters: split /([:%;])/.