--- lib/Hash/Flatten.pm.orig 2007-08-14 08:34:38.000000000 +0200 +++ lib/Hash/Flatten.pm 2007-08-14 08:35:11.000000000 +0200 @@ -19,6 +19,8 @@ use constant DEFAULT_HASH_DELIM => '.'; use constant DEFAULT_ARRAY_DELIM => ':'; +use constant RETURN_EMPTY_HASH_VALUES => 0; +use constant DEFAULT_EMPTY_HASH_VALUE => ''; #Check if we need to support overloaded stringification use constant HAVE_OVERLOAD => eval { @@ -36,6 +38,8 @@ #Defaults $self->{HashDelimiter} ||= DEFAULT_HASH_DELIM; $self->{ArrayDelimiter} ||= DEFAULT_ARRAY_DELIM; + $self->{EmptyHashValue} ||= DEFAULT_EMPTY_HASH_VALUE; + $self->{ReturnEmptyHashValues} ||= RETURN_EMPTY_HASH_VALUES; $self->{EscapeSequence} = "\\" unless(defined $self->{EscapeSequence} && length($self->{EscapeSequence}) > 0); #Sanity check: delimiters don't contain escape sequence @@ -204,6 +208,7 @@ die "Recursive data structure detected at this point in the structure: '$prefix'. Cannot flatten recursive structures."; } + return ($self->_flatten($prefix, $self->{EmptyHashValue}, $delim)) if (not keys %$hashref and $prefix and $self->{ReturnEmptyHashValues} ); my @flat; for my $k (keys %$hashref) { --- t/hash_flatten.t.orig 2007-08-14 08:35:05.000000000 +0200 +++ t/hash_flatten.t 2007-08-14 08:35:11.000000000 +0200 @@ -71,6 +71,92 @@ ############################################################# # +# Nested hashes with empty sub hashes +# +############################################################# + +my $data = +{ + 'x' => 1, + 'y' => { + 'a' => 2, + 'b' => { + 'p' => 3, + 'q' => 4, + 'r' => {}, + }, + } +}; + +my $flat_data = { + 'x' => 1, + 'y.a' => 2, + 'y.b.p' => 3, + 'y.b.q' => 4, +}; + +my $flat = Hash::Flatten::flatten($data); +DUMP($flat); +ASSERT EQUAL($flat, $flat_data), 'nested hashes with subhashes 1'; + +# subhashes can not be reconstructed +my $unflat = Hash::Flatten::unflatten($flat); +DUMP($unflat); +ASSERT EQUAL($unflat, { + 'x' => 1, + 'y' => { + 'a' => 2, + 'b' => { + 'p' => 3, + 'q' => 4, + }, + } + }), 'nested hashes with subhashes unflattened 1'; + +############################################################# + +my $data = +{ + 'x' => 1, + 'y' => { + 'a' => 2, + 'b' => { + 'p' => 3, + 'q' => 4, + 'r' => {}, + }, + } +}; + +my $flat_data = { + 'x' => 1, + 'y.a' => 2, + 'y.b.p' => 3, + 'y.b.q' => 4, + 'y.b.r' => '' +}; + +$flat = Hash::Flatten::flatten($data, {'ReturnEmptyHashValues' => 1, 'EmptyHashValue' => ''}); +DUMP($flat); +ASSERT EQUAL($flat, $flat_data), 'nested hashes with subhashes 2'; + +# subhashes can not be reconstructed +my $unflat = Hash::Flatten::unflatten($flat); +DUMP($unflat); +ASSERT EQUAL($unflat, { + 'x' => 1, + 'y' => { + 'a' => 2, + 'b' => { + 'p' => 3, + 'q' => 4, + 'r' => '', + }, + } + }), 'nested hashes with subhashes unflattened 2'; + +############################################################# +# # Mixed hashes/arrays # #############################################################