in reply to Splitting a string while respecting parentheses

Doing a proper job of rolling your own calls for character-by-character parsing. Parse::RecDescent is a worthwhile tool to learn, but if you'll never get more complicated than the OP task, this would probably suffice:
use strict; while (<DATA>) { chomp; my $nested = 0; my @out = (); my $tkn = ''; for my $c ( split // ) { if ( $c eq '(' ) { $nested++; $tkn .= $c; } elsif ( $c eq ')' ) { if ( $nested ) { $nested--; } else { warn "unmatched ')' in $_\n"; } $tkn .= $c; } elsif ( $nested or $c ne ',' ) { $tkn .= $c; } elsif ( $tkn ) { push @out, $tkn; $tkn = ''; } } if ( $nested ) { warn "$nested unmatched '(' in $_\n"; } else { push @out, $tkn if ( $tkn ); } print join( " ;; ", @out ), "\n" if ( @out ); } __DATA__ a,b,c,d x,z, a,(b,c(d,e)f)),h (1,2)(345) ,(6,7),(789) ((345,6),567 ,,m,,n,,(o,,p),,q,,

Replies are listed 'Best First'.
Re^2: Splitting a string while respecting parentheses
by norkakn (Novice) on Dec 08, 2008 at 16:04 UTC
    Thanks, this is the road I'll go down.