I need to parse command line arguments coming in from a ksh script.
Arguments come in with the following format...
key=value
The key may not have spaces or an equal sign in it.
The value may have any characters in it
An example would be something like...
vchtyp=I jrnltyp=D lexwhere="'in('DIS', 'DIM', 'DIR')'" title="'this i +s a title'"
Note that the lexwhere and title parameters have spaces in them.
I need the results to be put into a hash like...
$hash{vchtyp} = 'I' $hash{jrnltyp = 'D'; $hash{lexwhere} = "'in('DIS', 'DIM', 'DIR')'"; $hash{title} = "'this is a test'";
There must be an easier way to parse this than what I've come up with.
Here is my mess.
sub parseArgs { my (@args) = @_; my @chars = split(// , join(' ', @args)); my %params = (); my $label = ''; my $value = ''; my $inLabel = 0; my $inValue = 0; my $doubleQuotes = 0; my $singleQuotes = 0; my $isSpace = 0; my $isEquals = 0; my $isDoubleQuote = 0; my $isSingleQuote = 0; for my $char (@chars) { $isSpace = $char =~ /\s/; $isEquals = $char eq '='; $isDoubleQuote = $char eq '"'; $isSingleQuote = $char eq "'"; if ($inLabel) { if ($isEquals) { $inLabel = 0; $inValue = 1; } else { $label .= $char; } } elsif ($inValue) { $doubleQuotes++ if $isDoubleQuote; $singleQuotes++ if $isSingleQuote; if ($isSpace) { if (($singleQuotes % 2) == 0 && ($doubleQuotes % 2) == 0) +{ $inValue = 0; $params{$label} = $value; $label = ''; $value = ''; } else { $value .= $char; } } else { $value .= $char; } } elsif (!$isSpace) { $inLabel = 1; $label .= $char; } } if ($inValue && $label && $value) { $params{$label} = $value; } return %params; }
Does anyone have any suggestions?

Edit by thelenm: changed pre tags to code tags


In reply to parsing arguments by mifflin

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.