Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: Storing/parsing perl data structure in/from a file

by hdb (Prior)
on Jun 13, 2013 at 09:46 UTC ( #1038712=note: print w/ replies, xml ) Need Help??

in reply to Storing/parsing perl data structure in/from a file

Based on LanX' advice Re: Storing/parsing perl data structure in/from a file (YAML), it turns your data into an array of arrays, adding quotes in a simplistic way, and then traverses the resulting structure to turn it into a hash of hashes. It adds underscores to the keys to avoid duplicates. You might want to change that code to add a warning message.

use strict; use warnings; use Data::Dumper; my $data; { local $/; $data = <DATA> } $data =~ tr/}{/][/; $data =~ s/\s*(.*?)\s*=>\s*(.*?)\s*,/"$1","$2",/g; # warning: simplist +ic quoting my $aref; eval "\$aref=$data"; sub array2hash { my $aref = shift; return $aref if "ARRAY" ne ref $aref; die "Cannot turn array with odd number of elements into hash.\ +n" if @$aref %2; my $href = {}; for (0..@$aref/2-1) { $aref->[2*$_] .= "_" while( exists $href->{$aref->[2*$ +_]} ); $href->{$aref->[2*$_]} = array2hash( $aref->[2*$_+1] ) +; } return $href; } my $href = array2hash $aref; print Dumper $href; __DATA__ { alpha => { beta => { gamma => theta, delta => lambda, }, beta => { gamma => zeta, }, }, },

If you want the contents of several files into one hash, I would think the best strategy is to first read the contents of all files into one string, then turn it into array of arrays and then into hash of hashes.

Comment on Re: Storing/parsing perl data structure in/from a file
Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1038712]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (10)
As of 2015-07-02 10:09 GMT
Find Nodes?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...

    Results (33 votes), past polls