in reply to Complex Splitting

You can do this with a split but the pattern is a lot trickier than that for the global match. Advantage is you don't have to worry about grep'ing out undefined values.

use strict; use warnings; use Data::Dumper; my $str = q{ABC[GHI]XYZ}; my $rxSplit = qr {(?x) # use extended syntax (?: # non-capturing group \[ # literal opening square br. | # or \] # literal closing square br. | # or (?= # look-ahead, a point # followed by [^]]+ # one or more non-closing # square brs. (?: # non-capturing group # then either \[ # literal opening square br. | # or \z # end of string ) # close non-capturing group ) # close look-ahead ) # close non-capturing group }; my @array = split m{$rxSplit}, $str; print Data::Dumper->Dump([\@array], [qw{*array}]);

Here's the output.

@array = ( 'A', 'B', 'C', 'GHI', 'X', 'Y', 'Z' );

On balance, I'd go with the global match, something like holli's or eric256's solutions.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Complex Splitting
by Roy Johnson (Monsignor) on Feb 06, 2007 at 15:54 UTC
    I don't think it's a lot trickier. This oughta do it:
    @array = grep defined, split /(\[.*?\])|/;
    That is, if you split on a bracketed group, capture it. If you don't have a bracketed group, split on nothing. Then filter out where the capture didn't match.

    Caution: Contents may have been coded under pressure.
      Yes, I regretted the word "lot" as soon as I'd posted, made it sound as if I'd sweated blood writing it. Although I like the simpler approach of your solution there is one problem with it; it doesn't get rid of the square brackets, which was required by the OP.

      Cheers,

      JohnGG

        Hasty reading on my part. Not capturing the brackets is as simple as leaving them outside the capturing parentheses:
        @array = grep defined, split /\[(.*?)\]|/;

        Caution: Contents may have been coded under pressure.