http://www.perlmonks.org?node_id=1038712


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.