Assuming that there are no _extra_ commas or equal signs besides the ones that separate key/value pairs and separate the keys from the values, ...
my @stuff; while (<FILEHANDLE>) { chomp; push @stuff, { map {split /\s*=\s*/} split /,\s*/ } }
But don't just copy this code if you don't understand it, especially if this is going into something you'll have to maintain. Let's break that down into something more verbose...
First, the {} constructs a reference to a hash, so the code above is equivalent to this:
my @stuff; while (<FILEHANDLE>) { chomp; my %record = map {split /\s*=\s*/} split /,\s*/; push @stuff, \%record; }
split uses $_ by default and produces a list, so we could expand the above as follows...
my @stuff; while (<FILEHANDLE>) { chomp; my @keysandvalues; my @field = split /,\s*/, $_; foreach $f (@field) { my ($key, $value) = split /\s*=\s*/, $_; push @keysandvalues, $key; push @keysandvalues, $value; } my %record = @keysandvalues; push @stuff, \%record; }
The last version is quite verbose, and when you're comfortable with references and list operators you'll probably not like it, but you may want to stick with something more verbose like that for now if you understand it better than the shorter version.
Also, be aware that if there are any anomalies in the input, such as any missing or extra commas or equal signs, this code will produce quite strange results. I believe there is an extra argument you can optionally pass to split to limit the number of pieces it will split things into, which may be of value here. I'd look it up, but my camel is at home and I'm not. Perhaps someone else can reply and confirm whether it is the third argument as ISTR.
$;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/
In reply to Re: Parsing data into an Array of Hashes
by jonadab
in thread Parsing data into an Array of Hashes
by nimdokk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |