theNeuron has asked for the wisdom of the Perl Monks concerning the following question:
How to slice this string into an array?
"word1",word2,"word3,word4"
result should be [ 'word1', 'word2', 'word3,word4' ]
That is if the word is surrounded by apostroph don't include it into the result.
The regex seems to be simple: (?: "([^"]*)" | ([^,]) )(?:,|$), but to my surprise both the matched and unamtched parenthesis contribute to the result, making it something like
[ 'word1', undef, undef, 'word2', 'word3,word4', undef ]
I have tried to make use of %+ which should use the leftmost defined result. That works ok, but the code seems to be too unreadable for what it does:
while ( m/ (?: # non-capturing braces "(?<val>[^"]*)" # Find either string delimited by '"' | # or (?<val>[^,]*) # string up to next ',' ) (?:,|$) # After which there is either , or end of line /gx ) { push @input, $+{val}; }
I have tried to use @input = map { %+{val} } m/.../gx, but that fills the whole array with just the last match from whole string.
Is there a way to avoid the while + push loop and store the results in to array directly, just for the sake of making the code simpler and nicer?
Many thanks
__
Vlad
|
|---|