in reply to Replacing commas with pipes

Here is an example using Text::CSV_XS
use strict; use warnings; use Text::CSV_XS; my $csv = Text::CSV_XS->new(); # create a new object while (<DATA>) { my $status = $csv->parse($_); # parse a CSV string into fields my @columns = $csv->fields(); # get the parsed fields my $str = join '|', @columns; print "$str\n"; } __DATA__ a,b,c d,e,"f|g"

prints:

a|b|c d|e|f|g

Is this the output you are looking for?

Replies are listed 'Best First'.
Re^2: Replacing commas with pipes
by JavaFan (Canon) on May 11, 2009 at 19:32 UTC
    Your second example turns a 3 column record into a 4 column record. Now, it matches the specification as given, but if you go the CSV way, it doesn't seem to be a logical solution.

    Considering that Text::CSV_XS allows you to set the separator, it seems more logical to use two Text::CVS_XS objects: one to read, one to write.

      re JavaFan's comment about toolic's "...second example":

      /me thinks that's a typo in data (d,e,"f|g" should be d,e,"f,g"), as OP's spec has commas throughout...even inside the quotes.

      Update: rephrased to clarify first line with attributions.

      Update2: In fairness, JavaFan's s/("[^"]*")|,/$1||"|"/eg; appears to work with this data:

      "x,y,z",red,blue 1,"2,3",4,foo,bar,"blivitz_kung" a,b,"c,d,e,",nodereaper "Super_Search","XP per node",data,"code tags,markup" monk,troll,saint,"holders of unholy powers","Orders of Monks:novice,in +itiate,etc"

      (Update3: bah, humbug, copied wrong data. Fixed above.)

      producing this output:

      "x,y,z"|red|blue 1|"2,3"|4|foo|bar|"blivitz_kung" a|b|"c,d,e,"|nodereaper "Super_Search"|"XP per node"|data|"code tags,markup" monk|troll|saint|"holders of unholy powers"|"Orders of Monks:novice,in +itiate,etc"

      Nonetheless, given the likelihood of (unknown, unspecified) edge-cases, a well-tested module remains the way to go, IMO.