i'm trying to create a string tokenizer for a config file parser and the best that i've managed to think of is this:
#!/usr/bin/perl use strict; use Data::Dumper; my $line = q[keyword1 value keyword2 "value with spaces" keyword3 valu +e]; print Dumper tokenize_line($line); sub tokenize_line { my $line = shift; my @tokens; while ($line =~ /(\S+)/g) { # every non-space match is a token push @tokens, $1; # anything in double-quotes is a single token if ($line =~ /\G\s*"(.+?)"/) { push @tokens, $1; # continue from this last match $line = $'; } } return \@tokens; }
wich outputs this:
$VAR1 = [ 'keyword1', 'value', 'keyword2', 'value with spaces', 'keyword3', 'value' ];
i know it's an ugly hack, trying to substitute the original string with the rest of the matched pattern ($line = $';), but in my previous attempts i would use split and substr to achieve the same results... and it was very ugly :)
what would be a better way to write this? i will be parsing some hundred lines from a config file, so i don't think i want a performance penalty. thank you all for your time and advice!

:)))))

In reply to Re^2: use English; and performance by asz
in thread use English; and performance by asz

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.