I am trying to parse a simple string. In doing so, I want to get rid of quotes. The regex as it stands doesn't reflect the possibility of escaped quotes.

Let's take this string: '1,2,3,4,"fine","day","today",'

If I could remove all the qoutes (or didn't care) I could use:
@a = $string =~/ ( #capture matches and put them into @a (?:\d+) | (?:"(?:.+?)") ) /gx; print Dumper \@a;
to give me :
$VAR1 = [ '1', '2', '3', '4', '"fine"', '"day"', '"today"' ];
I don't wan't those quotes, so I :
@b = $string =~/ (?: #don't capture matches (\d+) | (?:"(.+?)") #capture numbers and anything inside of quotes ) /gx; print Dumper \@b;
which gives me:
$VAR1 = [ '1', undef, '2', undef, '3', undef, '4', undef, undef, 'fine', undef, 'day', undef, 'today' ];
Oh NO!!! all those undefs and I might want to use a hash instead of an array!! Oh, what can I do?
@c = map {/.+/g} #if it's an undef, it's NOT getting into that array ;) $string =~/ (?: (\d+) | (?:"(.+?)") ) /gx; print Dumper \@c;
to get:
$VAR1 = [ '1', '2', '3', '4', 'fine', 'day', 'today' ];
LOVELY!!

But why? Granted, this exercise has helped me to understand map() alot better, but I would like to know what it is about my pattern that creates all those undefs, and I would like to know how (if there's a way) I could do this without all those undefs.

I'm happy with my solution, but I'm unhappy with the fact that I don't understand the problem. If you have an idea about how to help me understand, I'd be very thankful.

---

($state{tired})?(sleep($wink * 40)): (eat($food));

In reply to Understanding regular expressions: why do I have to use map to clear up undefs in regex output? by corenth

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.