Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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

by hdb (Parson)
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2014-07-26 04:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (175 votes), past polls