Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: Parsing data into an Array of Hashes

by jonadab (Parson)
on Sep 18, 2003 at 13:04 UTC ( #292376=note: print w/replies, xml ) Need Help??

in reply to Parsing data into an Array of Hashes

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.

update: Added \s* and chomp in several places to better trim whitespace.

$;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/

Replies are listed 'Best First'.
Re: Re: Parsing data into an Array of Hashes
by nimdokk (Vicar) on Sep 18, 2003 at 13:16 UTC
    Thanks, that helps. I was working somewhat along these lines already but wasn't quite getting things put into the right spots. I'll poke around a bit more with this as the days go by (this is really a side project that I'm working on when I get frustrated with other things :)

    "Ex libris un peut de tout"

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://292376]
and monks are getting baked in the sun...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2017-03-30 18:42 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (362 votes). Check out past polls.