How do I split a string into an array by comma but ignore commas inside double quotes?

前端 未结 7 516
执笔经年
执笔经年 2020-12-22 07:50

I have a line:

$string = \'Paul,12,\"soccer,baseball,hockey\",white\';

I am try to split this into @array that has 4 values so

<         


        
7条回答
  •  借酒劲吻你
    2020-12-22 08:22

    In response to how to do it with Text::CSV(_PP). Here is a quick one.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Text::CSV_PP;
    my $parser = Text::CSV_PP->new();
    
    my $string = "Paul,12,\"soccer,baseball,hockey\",white";
    
    $parser->parse($string);
    my @fields = $parser->fields();
    
    print "$_\n" for @fields;
    

    Normally one would install Text::CSV or Text::CSV_PP through the cpan utility.

    To work around your not being able to install modules, I suggest you use the 'pure Perl' implementation so that you can 'install' it. The above example would work assuming you copied the text of Text::CSV_PP source into a file named CSV_PP.pm in a folder called Text created in the same directory as your script. You could also put it in some other location and use the use lib 'directory' method as discussed previously. See here and here to see other ways to get around install restriction using CPAN modules.

提交回复
热议问题