Mes Chers Moines,
I have set myself the following task:
  1. given a string which may or may not contain quoted strings within it
  2. count the quotes to make sure that there aren't an odd number
  3. if that test is passed, put the quoted strings in one array
  4. put the regular strings, split on whitespace, in another

So far I have something like this:

$string = 'one two "three" four "five" six'; $count_quotes = $string =~ tr/"/"/; if($count_quotes && ($count_quotes % 2 != 0)){ # there is an odd number of quotes in the string $quotedstringerror = 1; # use this to show user an error message later }elsif($count_quotes){ # there is an even number of quotes in the string $quotedstrings = 1; } if($quotedstrings){ @quotedstrings = $string =~ /"([^"]*?)"/g; # get them all out with m// $string =~ s/"[^"]*?"//g; # remove them from the original with s/// } @unquotedstrings = split(/ +/,$string); # grab remaining regular strings using split print "\@quotedstrings: @quotedstrings \n"; print "\@unquotedstrings: @unquotedstrings \n"; # output: @quotedstrings: three five # @unquotedstrings: one two four six

This seems to work OK, but could I be doing it in a better way?

Do I really have to use tr/// to count them (because m// doesn't return a number of matches), then use m// to get them out (because s/// doesn't push finds onto an array), then use s/// to clean up after myself?

I keep thinking there's something I've missed.
--

“Every bit of code is either naturally related to the problem at hand, or else it's an accidental side effect of the fact that you happened to solve the problem using a digital computer.”
M-J D

In reply to separated quoted stings from unquoted strings by Cody Pendant

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.