Wow... When I started working on this there were no posts. Now there's 3.
Well I'll post my own solution also, though I think I've already been outdone.
My approach is simple. First split on the space to an array & then iterate over it looking for '='
When it's found, assign to that key. Every value that follows is assumed to belong to that key until another is mentioned.
You did say the purpose here was to assign multiple values an an individual key, yes?
Well then assuming that your values don't contain commas, you could do something similar when extracting. Test for a ',' & if it exisits, split on it.
Anyway, here's my effort, I hope it helps:
#!e:\perl\bin\perl.exe -w
use strict;
my $data="key1=value1 key2=value2 value3 key4=value4 value5 value6 key
+5=value7 key6=value8 key7=value9 value10";
my @values=split(/ /,$data);
my ($h,$value, $v, $recentkey);
my %output;
my @hashkeys;
for $value(@values) {
if ($value =~ /=/) {
($recentkey, $v) = split(/=/,$value);
$output{$recentkey} = $v;
} else {
$output{$recentkey} .= ",$v";
}
}
@hashkeys = keys %output;
for $h(@hashkeys) {
print "$h: $output{$h} \n";
}
Wait! This isn't a Parachute, this is a Backpack!
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.