Well, with far less code, you could do the following:

my $string = q("one","two","three"); my @array = split( /"(?:,")?/, $string );

This will, however, create an empty element at the beginning of the list (the stuff before the opening quote of "one"). You could remove it afterwards with shift @array.

You could attempt to get rid of that extra element with a negative look-behind assertion:

my @array = split( /(?<!^)"(?:,")?/, $string );

But that has the undesirable property of returning a string equivalent to:

my @array = qw( "one two three );

Again, this is trivial to fix:

$array[0] =~ s/^"/;

But, as you can see, when what appears as very simple code turns out to require some weird make-work code to solve the "almost-there" case, there's something wrong. This is what is known as code smell. I think what you really want is to load a module, such as Text::CSV_XS (or Text::CSV), and be done with it.

Even if you think it's overkill in this instance, it doesn't cost you much to learn how to use it. In the long run, you will have learnt how to use it in a simple scenario, and that will pay off later when you have some much hairier CSV problems, and you might risk trying to extend this code a bit more, rather than using a proven module... and that's when you'll pay the full price of not having learnt it now when it was easy.

• another intruder with the mooring in the heart of the Perl


In reply to Re: Interpolating a string into list context. by grinder
in thread Interpolating a string into list context. by hangon

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.