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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1038712]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (9)
As of 2017-02-28 01:02 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (394 votes). Check out past polls.