I didn't have time yesterday to put this idea into code, but since no-one else did it meanwhile, here it is. The crux of the OP is the need for a tiny enhancement to split, which is as simple as this:
sub MySplit2 { # args being like split but with the third INSTEAD a # preservation delimiter -- the OP requirement seems # to suggest that should be -1 for split anyway my $pat = shift; my $str = ( shift () || $_ ); my $pat2 = shift; # a preservation delimiter # i.e. not splits usual arg3 my @return = (); my $inquotes = 0; for my $qs ( defined ( $pat2 ) ? ( split( /$pat2/, $str, -1 ) ) : ( $str ) ) { push @return, $inquotes ? $qs : split( /$pat/, $qs, -1 ); $inquotes = !$inquotes; } return @return; }
But even if taken to the extreme of including all split's existing bells and whistles, it still manages to remain reasonable in size:
# example: # while (<FILE>) { # ( $name, $address, $tel ) = MySplit( ',',,,'"' ); # } sub MySplit { # a wrapper for split # args being like split but with a fourth for optional # preservation delimiter my $pat = shift; my $str = ( shift () || $_ ); my $cnt = shift; # copy of split's normal third argument # will be iterated down to zero here my $pat2 = shift; # the new argument my @return = (); my @topush; my $inquotes = 0; for my $qs ( defined ( $pat2 ) ? ( split( /$pat2/, $str, -1 ) ) : ( $str ) ) { $cnt or ( defined( $cnt ) and last ); # arg3>0 exhaustion @topush = $inquotes ? ($qs) : split( /$pat/, $qs, $cnt ); # update @topush and $cnt to agree with each other if ( defined( $cnt ) and ( $cnt >= 0 ) ) { $cnt -= ( $#topush + 1 ); if ( $cnt < 0 ) $#topush += $cnt; $cnt = 0; } } $inquotes = !$inquotes; push @return, @topush; } return @return; }

-M

Free your mind


In reply to Re: CSV file by Moron
in thread CSV file by azaria

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.