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

What i want to do is split a comma delimited string on all commas that are not preceded by a "\"

that is:
my $str = 'this,is\,a,string';
should be broken up into "this", "is\,a", "string"

I tried the following segment of code:
my @splits = split(/[^\\],/,$str);
which works, except, that it uses the character directly before the comma as part of the split. The above RE gives me the following:
"thi", "is\,", "strin"

What would be the best way to split this line?

Replies are listed 'Best First'.
Re: RE Dropping last Character
by Anonymous Monk on Jun 11, 2003 at 18:44 UTC

    my  @splits = split(/(?<!\\),/,$str);

      And since we're supposed to be learning something here =)...

      "(?<!pattern)"
      A zero-width negative look-behind assertion. For example "/(?<!bar)foo/" matches any occurrence of "foo" that does not follow "bar". Works only for fixed-width look-behind.

      That's right, a negative, look-behind assertion. It's under "Extended Patterns" in perldoc perlre.

      --
      Allolex

Re: RE Dropping last Character
by cciulla (Friar) on Jun 11, 2003 at 18:55 UTC

    Kludgey in the extreme, but this works...

    $_ = 'this,is\,a,string'; s/\\,/\x0/g; foreach (split /,/) { s/\x0/\\,/; print "$_\n"; }