I am trying to do a split on a string with comma delimiter
my $string=\'ab,12,20100401,xyz(A,B)\';
my @array=split(\',\',$string);
If I do
Here is my attempt. It should handle depth well and could even be extended to include other bracketed symbols easily (though harder to be sure that they MATCH). This method will not in general work for quotation marks rather than brackets.
#!/usr/bin/perl
use strict;
use warnings;
my $string='ab,12,20100401,xyz(A(2,3),B)';
print "$_\n" for parse($string);
sub parse {
my ($string) = @_;
my @fields;
my @comma_separated = split(/,/, $string);
my @to_be_joined;
my $depth = 0;
foreach my $field (@comma_separated) {
my @brackets = $field =~ /(\(|\))/g;
foreach (@brackets) {
$depth++ if /\(/;
$depth-- if /\)/;
}
if ($depth == 0) {
push @fields, join(",", @to_be_joined, $field);
@to_be_joined = ();
} else {
push @to_be_joined, $field;
}
}
return @fields;
}