Hash-Flatten-1.19/0000755016522100007720000000000011447132406015175 5ustar jamielengineers00000000000000Hash-Flatten-1.19/t/0000755016522100007720000000000011447132405015437 5ustar jamielengineers00000000000000Hash-Flatten-1.19/t/pod_coverage.t0000644016522100007720000000033011447132364020261 0ustar jamielengineers00000000000000use Test::More; eval "use Test::Pod::Coverage 1.00"; plan skip_all => "Test::Pod::Coverage 1.00 required for testing POD Coverage" if $@; all_pod_coverage_ok({ also_private => [ qr/^[A-Z_]+$/ ], }); #Ignore all caps Hash-Flatten-1.19/t/data.lib0000644016522100007720000000035511447132362017045 0ustar jamielengineers00000000000000use vars qw($data $flat_data); $data = { 'x' => 1, 'y' => { 'a' => 2, 'b' => { 'p' => 3, 'q' => 4 }, } }; $flat_data = { 'x' => 1, 'y.a' => 2, 'y.b.p' => 3, 'y.b.q' => 4 };Hash-Flatten-1.19/t/hash_flatten.t0000644016522100007720000002527511447132362020301 0ustar jamielengineers00000000000000#!/usr/local/bin/perl -w ############################################################################### # Purpose : Unit test for Hash::Flatten # Author : John Alden # Created : Feb 2002 # CVS : $Header: /home/cvs/software/cvsroot/hash_flatten/t/hash_flatten.t,v 1.21 2009/05/09 12:42:02 jamiel Exp $ ############################################################################### # -t : trace # -T : deep trace into modules ############################################################################### use strict; use Test::Assertions qw(test); use Getopt::Std; use Log::Trace; use vars qw($opt_t $opt_T); getopts("tT"); plan tests; #Compile the code chdir($1) if($0 =~ /(.*)(\/|\\)(.*)/); unshift @INC, "./lib", "../lib"; #Override warn() first, then compile my $buf; { BEGIN {$^W = 0} *CORE::GLOBAL::warn = sub {$buf = shift()}; require Hash::Flatten; } ASSERT($INC{'Hash/Flatten.pm'}, 'loaded'); import Log::Trace qw(print) if ($opt_t); deep_import Log::Trace qw(print) if ($opt_T); ############################################################# # # Nested hashes # ############################################################# my $data = { 'x' => 1, 'y' => { 'a' => 2, 'b' => { 'p' => 3, 'q' => 4 }, } }; 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'; my $unflat = Hash::Flatten::unflatten($flat); DUMP($unflat); ASSERT EQUAL($unflat, $data), 'nested hashes unflattened'; ############################################################# # # Nested hashes with weird values # ############################################################# my $data = { 'x' => 1, '0' => { '1' => 2, '' => { '' => 3, 'q' => 4 }, }, 'a' => [1,2,3], '' => [4,5,6], }; my $flat_data = { 'x' => 1, '0.1' => 2, '0..' => 3, '0..q' => 4, 'a:0' => 1, 'a:1' => 2, 'a:2' => 3, ':0' => 4, ':1' => 5, ':2' => 6, }; my $flat = Hash::Flatten::flatten($data); DUMP($flat); ASSERT EQUAL($flat, $flat_data), 'nested hashes with weird values'; my $unflat = Hash::Flatten::unflatten($flat); DUMP($unflat); ASSERT EQUAL($unflat, $data), 'nested hashes with weird values unflattened'; ############################################################# # # Mixed hashes/arrays # ############################################################# my $foo = 'hello'; $data = { 'x' => 1, 'ay' => { 'a' => 2, 'b' => { 'p' => 3, 'q' => 4 }, }, 's' => \\\$foo, 'y' => [ 'a', 2, { 'baz' => 'bum', }, ] }; $flat_data = { 'ay*b*p' => 3, 'ay*b*q' => 4, 's' => 'hello', 'ay*a' => 2, 'y%2*baz' => 'bum', 'x' => 1, 'y%0' => 'a', 'y%1' => 2 }; $flat = Hash::Flatten::flatten($data, {'HashDelimiter' => '*', 'ArrayDelimiter' => '%'}); DUMP($flat); ASSERT EQUAL($flat, $flat_data), 'heterogeneous structure'; $unflat = Hash::Flatten::unflatten($flat, {'HashDelimiter' => '*', 'ArrayDelimiter' => '%'}); DUMP($unflat); ASSERT EQUAL($unflat, { ### NB we can't compare to $data here because we flatten out scalar refs 'x' => 1, 'y' => [ 'a', 2, { 'baz' => 'bum' } ], 'ay' => { 'a' => 2, 'b' => { 'p' => 3, 'q' => 4 } }, 's' => 'hello' } ), 'heterogeneous structure unflattened'; ############################################################# # # Deeply nested arrays # ############################################################# $data = { 'x' => 1, 'y' => [ [ 'a', 'fool', 'is', ], [ 'easily', [ 'parted', 'from' ], 'his' ], 'money', ] }; $flat_data = { 'y:1:2' => 'his', 'x' => 1, 'y:1:1:0' => 'parted', 'y:1:1:1' => 'from', 'y:2' => 'money', 'y:0:0' => 'a', 'y:1:0' => 'easily', 'y:0:1' => 'fool', 'y:0:2' => 'is' }; $flat = Hash::Flatten::flatten($data); DUMP($flat); ASSERT EQUAL($flat, $flat_data), 'nested arrays'; $unflat = Hash::Flatten::unflatten($flat); DUMP($unflat); ASSERT EQUAL($unflat, $data), 'nested arrays unflattened'; ############################################################# # # Trivial cases # ############################################################# $data = { }; $flat_data = { }; $flat = Hash::Flatten::flatten($data); DUMP($flat); ASSERT EQUAL($flat, $flat_data), 'empty hash'; $unflat = Hash::Flatten::unflatten($flat); DUMP($unflat); ASSERT EQUAL($unflat, $data), 'empty hash unflattened'; $data = { 'x' => 1, }; $flat_data = { 'x' => 1, }; $flat = Hash::Flatten::flatten($data); DUMP($flat); ASSERT EQUAL($flat, $flat_data), '1 key'; $unflat = Hash::Flatten::unflatten($flat); DUMP($unflat); ASSERT EQUAL($unflat, $data), '1 key unflattened'; ############################################################# # # Very long delimiters # ########################################################### $data = { 'x' => 1, 'ay' => { 'a' => 2, 'b' => { 'p' => 3, 'q' => 4 }, }, 's' => 'hey', 'y' => [ 'a', 2, { 'baz' => 'bum', }, ] }; $flat_data = { 'x' => 1, 's' => 'hey', 'ay*Issa Hash*a' => 2, 'y%This Is an Array!!%%2*Issa Hash*baz' => 'bum', 'ay*Issa Hash*b*Issa Hash*p' => 3, 'y%This Is an Array!!%%0' => 'a', 'ay*Issa Hash*b*Issa Hash*q' => 4, 'y%This Is an Array!!%%1' => 2 }; $flat = Hash::Flatten::flatten($data, {'HashDelimiter' => '*Issa Hash*', 'ArrayDelimiter' => '%This Is an Array!!%%'}); DUMP($flat); ASSERT EQUAL($flat, $flat_data), 'long delimiters'; $unflat = Hash::Flatten::unflatten($flat, {'HashDelimiter' => '*Issa Hash*', 'ArrayDelimiter' => '%This Is an Array!!%%'}); DUMP($unflat); ASSERT EQUAL($unflat, $data), 'long delimiters unflattened'; ########################################################### # # Scalar refs, blessed refs etc # ########################################################### my $scal = 'scalar'; my $again = 'again!'; $data = bless({ 'x' => bless({'foo'=>'bar'}, 'Foo::Hash'), 'y' => bless(['f', 'g'], 'Bar::Array'), 'z' => bless(\$scal, 'Qux:Scalar'), 'r' => bless(\\\\\$again, 'Qux Ref'), 'rina' => [\$scal, \\$again], 'gref' => \*FH, }, 'Template'); DUMP($data); $flat_data = { 'z' => 'scalar', 'r' => 'again!', 'x.foo' => 'bar', 'y:0' => 'f', 'y:1' => 'g', 'rina:0' => 'scalar', 'rina:1' => 'again!', 'gref' => \*FH, }; $flat = Hash::Flatten::flatten($data); DUMP($flat); ASSERT EQUAL($flat, $flat_data), 'blessed references'; $unflat = Hash::Flatten::unflatten($flat); DUMP($unflat); ASSERT EQUAL($unflat, { 'x' => { 'foo' => 'bar' }, 'y' => [ 'f', 'g' ], 'r' => 'again!', 'z' => 'scalar', 'rina' => ['scalar', 'again!'], 'gref' => \*FH, }), 'objects and blessed refs unflattened'; ########################################################### # # OO Interface and callbacks # ########################################################### my $counter = 0; my $o = new Hash::Flatten({ 'OnRefRef' => sub { my $v = shift; $counter++; return $$v; #follow }, 'OnRefScalar' => sub { my $v = shift; $counter--; return $$v; #follow }, 'OnRefGlob' => sub { my $v = shift; $counter--; return "A-GLOB"; } }); # Test coderef for handling refs $flat = $o->flatten({a => \\\\\"x"}); DUMP($flat); ASSERT($counter == 3, "coderef called $counter times"); $flat = $o->flatten({a => \*FH}); DUMP($flat); ASSERT($counter == 2 && $flat->{a} eq 'A-GLOB', "globref callback"); ########################################################### # # Escaping # ########################################################### my $orig = { a => ['1.1', '1.2', '2.1'], 'b:c' => {e => '3.1'} }; $flat = Hash::Flatten::flatten($orig); DUMP($flat); $unflat = Hash::Flatten::unflatten($flat); DUMP($unflat, $orig); ASSERT(EQUAL($orig, $unflat), "escaping"); $orig = {'a' => {'A[ESC]B' => 'c[ESC]', 'C.D' => 'd:e'}}; $flat = Hash::Flatten::flatten($orig, {EscapeSequence => '[ESC]'}); DUMP($flat); $unflat = Hash::Flatten::unflatten($flat, {EscapeSequence => '[ESC]'}); DUMP($unflat, $orig); ASSERT(EQUAL($orig, $unflat), "custom escape seq"); ########################################################### # # Error checking # ########################################################### ASSERT(DIED( sub{ Hash::Flatten::flatten([1,2,3]) } ) && scalar $@ =~ /1st arg must be a hashref/, "type check in flatten"); ASSERT(DIED( sub{ Hash::Flatten::unflatten([1,2,3]) } ) && scalar $@ =~ /1st arg must be a hashref/, "type check in unflatten"); ASSERT( DIED( sub{ Hash::Flatten::flatten({}, {EscapeSequence => '.'}) }) && scalar $@ =~ /Hash delimiter cannot contain escape sequence/ , "check hash delim for esc seq"); ASSERT( DIED( sub{ Hash::Flatten::flatten({}, {EscapeSequence => ':'}) }) && scalar $@ =~ /Array delimiter cannot contain escape sequence/ , "check array delim for esc seq"); $data = { 'y' => { 'a' => 2, 'b' => 3 }, }; $data->{'y'}->{'c'} = $data; DUMP($data); ASSERT( DIED( sub { Hash::Flatten::flatten( $data ) } ), 'recursive data structure detected in hashref'); $data = { 'y' => { 'a' => 2, 'b' => 3 }, }; $data->{y}->{c} = \$data; DUMP($data); ASSERT( DIED( sub { Hash::Flatten::flatten( $data ) } ), "recursive data structure detected in ref-ref"); $data = { 'y' => { 'a' => 2, 'b' => 3 }, }; $data->{'y'}->{'c'} = [1]; push @{$data->{'y'}->{'c'}}, $data->{'y'}->{'c'}; DUMP($data); ASSERT( DIED( sub { Hash::Flatten::flatten( $data ) } ), "recursive data structure detected in arrayref"); ASSERT( DIED( sub{ Hash::Flatten::flatten({a => \[1,2]}, {OnRefRef => "die"}) }) && scalar $@ =~ /is a REF/ , "check ref to ref raises exception"); ASSERT( DIED( sub{ Hash::Flatten::flatten({a => \"x"}, {OnRefScalar => "die"}) }) && scalar $@ =~ /is a SCALAR/ , "check ref to scalar raises exception"); ASSERT( DIED( sub{ Hash::Flatten::flatten({a => \*FH}, {OnRefGlob => "die"}) }) && scalar $@ =~ /is a GLOB/ , "check ref to glob raises exception"); my $rv = Hash::Flatten::flatten({a => \[1,2]}, {OnRefRef => "warn"}); DUMP($rv); TRACE($buf); ASSERT(scalar $buf =~ /is a REF and will be followed/ && EQUAL($rv, { 'a:0' => 1, 'a:1' => 2 }), "warn mode works as expected"); $rv = Hash::Flatten::flatten({a=>"m:o.o", "o:i.n:k" => {a=>1}},{EscapeSequence => "#", DisableEscapes => 0}); DUMP($rv); ASSERT( EQUAL($rv,{a => 'm:o.o','o#:i#.n#:k.a' => 1}), "Escapes on, returned escaped hash" ); $rv = Hash::Flatten::unflatten({a => 'm:o.o','o#:i#.n#:k.a' => 1},{EscapeSequence => "#", DisableEscapes => 0}); DUMP($rv); ASSERT( EQUAL($rv,{a=>"m:o.o", "o:i.n:k" => {a=>1}}), "Escapes on, unescaped hash correctly" ); $rv = Hash::Flatten::flatten({a=>"m:o.o", "o:i.n:k" => {a=>1}},{EscapeSequence => "#", DisableEscapes => 1}); DUMP($rv); ASSERT( EQUAL($rv,{a => 'm:o.o','o:i.n:k.a' => 1}), "Escapes off, returned nonsense" ); $rv = Hash::Flatten::unflatten({a => 'm:o.o','o#:i#.n#:k.a' => 1},{EscapeSequence => "#", DisableEscapes => 1}); DUMP($rv); ASSERT( EQUAL($rv,{a => 'm:o.o','o#' => [{'n#' => [{a => 1}]}]}), "Escapes off, didn't unescape hash" ); Hash-Flatten-1.19/t/pod.t0000644016522100007720000000020111447132364016403 0ustar jamielengineers00000000000000use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok(); Hash-Flatten-1.19/t/overload.t0000644016522100007720000000365211447132362017447 0ustar jamielengineers00000000000000#!/usr/local/bin/perl -w ############################################################################### # Purpose : Unit test for Hash::Flatten with overload # Author : John Alden based on a bug report from Marcel Grünauer # Created : Oct 2005 # CVS : $Header: /home/cvs/software/cvsroot/hash_flatten/t/overload.t,v 1.3 2006/04/11 13:43:30 mattheww Exp $ ############################################################################### # -t : trace # -T : deep trace into modules ############################################################################### use strict; use Test::Assertions qw(test); use Getopt::Std; use Log::Trace; use vars qw($opt_t $opt_T); getopts("tT"); plan tests; #Compile the code chdir($1) if($0 =~ /(.*)(\/|\\)(.*)/); unshift @INC, "./lib", "../lib"; require Hash::Flatten; #Optional tracing import Log::Trace qw(print) if ($opt_t); deep_import Log::Trace qw(print) if ($opt_T); my $expected = { 'x.bar.value' => 1, 'x.baz.value' => 2 }; #Package without overload package PkgSansOverload; $PkgSansOverload::Counter=0; sub new { bless { value => ++$PkgSansOverload::Counter }, shift } #Package with overloaded string (if overload is available) package PkgWithOverload; $PkgWithOverload::Counter=0; eval { require overload; import overload '""' => sub { 'blah' }; }; sub new { bless { value => ++$PkgWithOverload::Counter }, shift } ######################################### # The tests ######################################### package main; my $data = {'x' => {}}; $data->{'x'}{'bar'} = PkgSansOverload->new; $data->{'x'}{'baz'} = PkgSansOverload->new; my $flat = Hash::Flatten::flatten($data); DUMP($flat); ASSERT(EQUAL($flat, $expected), "expected value without overload"); $data = {'x' => {}}; $data->{'x'}{'bar'} = PkgWithOverload->new; $data->{'x'}{'baz'} = PkgWithOverload->new; $flat = Hash::Flatten::flatten($data); DUMP($flat); ASSERT(EQUAL($flat, $expected), "same value with overloaded stringify"); Hash-Flatten-1.19/COPYING0000644016522100007720000004313111447132362016233 0ustar jamielengineers00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. Hash-Flatten-1.19/Changes0000644016522100007720000000107611447132362016475 0ustar jamielengineers00000000000000Thu Sep 23 09:52:13 2010 - 1.19 * Fix handling of 0 and '' key values (thanks to Fabrice Dulaunoy) * Update docs to reflect behaviour: EscapeSequence=undef doesn't work, you need to use the DisableEscapes Option (thanks to Fischer Ronald) Tue Apr 11 14:44:55 2006 - 1.16 * modified default escape sequence handling (bug fix) * unit tests now change into t/ directory correctly under windows environment Thu Oct 27 21:13:21 2005 - 1.15 Fix for overload thanks to Marcel Grünauer Fri Oct 22 15:49:15 2004 - 1.35 - Public release (CPAN) Hash-Flatten-1.19/lib/0000755016522100007720000000000011447132405015742 5ustar jamielengineers00000000000000Hash-Flatten-1.19/lib/Hash/0000755016522100007720000000000011447132405016625 5ustar jamielengineers00000000000000Hash-Flatten-1.19/lib/Hash/Flatten.pm0000644016522100007720000003024711447132362020570 0ustar jamielengineers00000000000000############################################################################### # Purpose : Flatten/Unflatten nested data structures to/from key-value form # Author : John Alden # Created : Feb 2002 # CVS : $Id: Flatten.pm,v 1.19 2009/05/09 12:42:02 jamiel Exp $ ############################################################################### package Hash::Flatten; use strict; use Exporter; use Carp; use vars qw(@ISA @EXPORT_OK %EXPORT_TAGS $VERSION); @ISA = qw(Exporter); @EXPORT_OK = qw(flatten unflatten); %EXPORT_TAGS = ('all' => \@EXPORT_OK); $VERSION = ('$Revision: 1.19 $' =~ /([\d\.]+)/)[0]; use constant DEFAULT_HASH_DELIM => '.'; use constant DEFAULT_ARRAY_DELIM => ':'; #Check if we need to support overloaded stringification use constant HAVE_OVERLOAD => eval { require overload; }; sub new { my ($class, $options) = @_; $options = {} unless ref $options eq 'HASH'; my $self = { %$options }; #Defaults $self->{HashDelimiter} ||= DEFAULT_HASH_DELIM; $self->{ArrayDelimiter} ||= DEFAULT_ARRAY_DELIM; $self->{EscapeSequence} = "\\" unless(defined $self->{EscapeSequence} && length($self->{EscapeSequence}) > 0); $self->{EscapeSequence} = undef if($self->{DisableEscapes}); #Sanity check: delimiters don't contain escape sequence croak("Hash delimiter cannot contain escape sequence") if($self->{HashDelimiter} =~ /\Q$self->{EscapeSequence}\E/); croak("Array delimiter cannot contain escape sequence") if($self->{ArrayDelimiter} =~ /\Q$self->{EscapeSequence}\E/); TRACE(__PACKAGE__." constructor - $self"); return bless($self, $class); } sub flatten { #Convert functional to OO with default ctor if(ref $_[0] ne __PACKAGE__) { return __PACKAGE__->new($_[1])->flatten($_[0]); } my ($self, $hashref) = @_; die("1st arg must be a hashref") unless(UNIVERSAL::isa($hashref, 'HASH')); my $delim = { 'HASH' => $self->{HashDelimiter}, 'ARRAY' => $self->{ArrayDelimiter} }; $self->{RECURSE_CHECK} = {}; my @flat = $self->_flatten_hash_level($hashref,$delim); my %flat_hash = map {$_->[0], $_->[1]} @flat; return \%flat_hash; } sub unflatten { #Convert functional to OO with default ctor if(ref $_[0] ne __PACKAGE__) { return __PACKAGE__->new($_[1])->unflatten($_[0]); } my ($self, $hashref) = @_; die("1st arg must be a hashref") unless(UNIVERSAL::isa($hashref, 'HASH')); my $delim = { 'HASH' => $self->{HashDelimiter}, 'ARRAY' => $self->{ArrayDelimiter} }; my $regexp = '((?:' . quotemeta($delim->{'HASH'}) . ')|(?:' . quotemeta($delim->{'ARRAY'}) . '))'; if($self->{EscapeSequence}) { $regexp = '(?{EscapeSequence}).')'.$regexp; #Use negative look behind } TRACE("regex = /$regexp/"); my %expanded; foreach my $key (keys %$hashref) { my $value = $hashref->{$key}; my @levels = split(/$regexp/, $key); my $finalkey = $self->_unescape((scalar(@levels) % 2 ? pop(@levels) : ''), $self->{EscapeSequence}); my $ptr = \%expanded; while (@levels >= 2) { my $key = $self->_unescape(shift(@levels), $self->{EscapeSequence}); my $type = shift(@levels); if ($type eq $delim->{'HASH'}) { if (UNIVERSAL::isa($ptr, 'HASH')) { $ptr->{$key} = {} unless exists $ptr->{$key}; $ptr = $ptr->{$key}; } else { $ptr->[$key] = {} unless defined $ptr->[$key]; $ptr = $ptr->[$key]; } } elsif ($type eq $delim->{'ARRAY'}) { if (UNIVERSAL::isa($ptr, 'HASH')) { $ptr->{$key} = [] unless exists $ptr->{$key}; $ptr = $ptr->{$key}; } else { $ptr->[$key] = [] unless defined $ptr->[$key]; $ptr = $ptr->[$key]; } } else { die "Type '$type' was not recognized. This should not happen."; } } if (UNIVERSAL::isa($ptr, 'HASH')) { $ptr->{$finalkey} = $value; } else { $ptr->[$finalkey] = $value; } } return \%expanded; } # # Private subroutines # sub _flatten { my($self, $flatkey, $v, $delim) = @_; TRACE("flatten: $self - " . ref($v)); if(UNIVERSAL::isa($v, 'REF')) { $v = $self->_follow_refs($v); } if(UNIVERSAL::isa($v, 'HASH')) { return $self->_flatten_hash_level($v, $delim, $flatkey); } elsif(UNIVERSAL::isa($v, 'ARRAY')) { return $self->_flatten_array_level($v, $delim, $flatkey); } elsif(UNIVERSAL::isa($v, 'GLOB')) { $v = $self->_flatten_glob_ref($v); } elsif(UNIVERSAL::isa($v, 'SCALAR')) { $v = $self->_flatten_scalar_ref($v); } return [$flatkey, $v]; } sub _follow_refs { my ($self, $rscalar) = @_; while (UNIVERSAL::isa($rscalar, 'REF')) { if ($self->{RECURSE_CHECK}{_stringify_ref($rscalar)}++) { die "Recursive data structure detected. Cannot flatten recursive structures."; } if(defined $self->{OnRefRef}) { if(ref $self->{OnRefRef} eq 'CODE') { TRACE("Executing coderef"); $rscalar = $self->{OnRefRef}->($rscalar); next; } elsif($self->{OnRefRef} eq 'warn') { warn("$rscalar is a ".(ref $rscalar)." and will be followed"); } elsif($self->{OnRefRef} eq 'die') { die("$rscalar is a ".(ref $rscalar)); } } $rscalar = $$rscalar; } return $rscalar; } sub _flatten_hash_level { my ($self, $hashref, $delim, $prefix) = @_; TRACE("_flatten_hash_level called"); if ($self->{RECURSE_CHECK}{_stringify_ref($hashref)}++) { die "Recursive data structure detected at this point in the structure: '$prefix'. Cannot flatten recursive structures."; } my @flat; for my $k (keys %$hashref) { TRACE("_flatten_hash_level: flattening: $k"); my $v = $hashref->{$k}; $k = $self->_escape($k, $self->{EscapeSequence}, [values %$delim]); my $flatkey = (defined($prefix) ? $prefix.$delim->{'HASH'}.$k : $k); push @flat, $self->_flatten($flatkey, $v, $delim); } return @flat; } sub _flatten_array_level { my ($self, $arrayref, $delim, $prefix) = @_; if ($self->{RECURSE_CHECK}{_stringify_ref($arrayref)}++) { die "Recursive data structure detected at this point in the structure: '$prefix'. Cannot flatten recursive structures."; } my @flat; foreach my $ind (0 .. $#$arrayref) { my $flatkey = (defined($prefix) ? $prefix.$delim->{'ARRAY'}.$ind : $ind); my $v = $arrayref->[$ind]; push @flat, $self->_flatten($flatkey, $v, $delim); } return @flat; } sub _flatten_scalar_ref { my ($self, $rscalar) = @_; if(defined $self->{OnRefScalar}) { if(ref $self->{OnRefScalar} eq 'CODE') { TRACE("Executing coderef"); return $self->{OnRefScalar}->($rscalar); } elsif($self->{OnRefScalar} eq 'warn') { warn("$rscalar is a ".(ref $rscalar)." and will be followed"); } elsif($self->{OnRefScalar} eq 'die') { die("$rscalar is a ".(ref $rscalar)); } } return $$rscalar; } sub _flatten_glob_ref { my($self, $rglob) = @_; if(defined $self->{OnRefGlob}) { if(ref $self->{OnRefGlob} eq 'CODE') { TRACE("Executing coderef"); return $self->{OnRefGlob}->($rglob); } elsif($self->{OnRefGlob} eq 'warn') { warn("$rglob is a ".(ref $rglob)." and will be followed"); } elsif($self->{OnRefGlob} eq 'die') { die("$rglob is a ".(ref $rglob)); } } return $rglob; } sub _escape { my ($self, $string, $eseq, $delim) = @_; return $string unless($eseq); #no-op $delim = [] unless(ref $delim eq 'ARRAY'); foreach my $char($eseq, @$delim) { next unless(defined $char && length($char)); $string =~ s/\Q$char\E/$eseq$char/sg; } return $string; } sub _unescape { my ($self, $string, $eseq) = @_; return $string unless($eseq); #no-op #Remove escape characters apart from double-escapes $string =~ s/\Q$eseq\E(?!\Q$eseq\E)//gs; #Fold double-escapes down to single escapes $string =~ s/\Q$eseq$eseq\E/$eseq/gs; return $string; } sub _stringify_ref { my $ref = shift; return unless ref($ref); #Undef if not a reference return overload::StrVal($ref) if(HAVE_OVERLOAD && overload::Overloaded($ref)); return $ref.''; #Force type conversion here } #Log::Trace stubs sub TRACE {} sub DUMP {} 1; =head1 NAME Hash::Flatten - flatten/unflatten complex data hashes =head1 SYNOPSIS # Exported functions use Hash::Flatten qw(:all); $flat_hash = flatten($nested_hash); $nested_hash = unflatten($flat_hash); # OO interface my $o = new Hash::Flatten({ HashDelimiter => '->', ArrayDelimiter => '=>', OnRefScalar => 'warn', }); $flat_hash = $o->flatten($nested_hash); $nested_hash = $o->unflatten($flat_hash); =head1 DESCRIPTION Converts back and forth between a nested hash structure and a flat hash of delimited key-value pairs. Useful for protocols that only support key-value pairs (such as CGI and DBMs). =head2 Functional interface =over 4 =item $flat_hash = flatten($nested_hash, \%options) Reduces a nested data-structure to key-value form. The top-level container must be hashref. For example: $nested = { 'x' => 1, 'y' => { 'a' => 2, 'b' => 3 }, 'z' => [ 'a', 'b', 'c' ] } $flat = flatten($nested); use Data::Dumper; print Dumper($flat); $VAR1 = { 'y.a' => 2, 'x' => 1, 'y.b' => 3, 'z:0' => 'a', 'z:1' => 'b', 'z:2' => 'c' }; The C<\%options> hashref can be used to override the default behaviour (see L). =item $nested_hash = unflatten($flat_hash, \%options) The unflatten() routine takes the flattened hash and returns the original nested hash (see L though). =back =head2 OO interface =over 4 =item $o = new Hash::Flatten(\%options) Options can be squirreled away in an object (see L) =item $flat = $o->flatten($nested) Flatten the structure using the options stored in the object. =item $nested = $o->unflatten($flat) Unflatten the structure using the options stored in the object. =back =head1 OPTIONS =over 4 =item HashDelimiter and ArrayDelimiter By default, hash dereferences are denoted by a dot, and array dereferences are denoted by a colon. However you may change these characters to any string you want, because you don't want there to be any confusion as to which part of a string is the 'key' and which is the 'delimiter'. You may use multicharacter strings if you prefer. =item OnRefScalar and OnRefRef and OnRefGlob Behaviour if a reference of this type is encountered during flattening. Possible values are 'die', 'warn' (default behaviour but warns) or a coderef which is passed the reference and should return the flattened value. By default references to references, and references to scalars, are followed silently. =item EscapeSequence This is the character or sequence of characters that will be used to escape the hash and array delimiters. The default escape sequence is '\\'. The escaping strategy is to place the escape sequence in front of delimiter sequences; the escape sequence itself is escaped by replacing it with two instances. =item DisableEscapes Stop the escaping from happening. No escape sequences will be added to flattened output, nor interpreted on the way back. B If your structure has keys that contain the delimiter characters, it will not be possible to unflatten the structure correctly. =back =head1 CAVEATS Any blessings will be discarded during flattening, so that if you flatten an object you must re-bless() it on unflattening. Note that there is no delimiter for scalar references, or references to references. If your structure to be flattened contains scalar, or reference, references these will be followed by default, i.e. C<'foo' =E \\\\\\$foo> will be collapsed to C<'foo' =E $foo>. You can override this behaviour using the OnRefScalar and OnRefRef constructor option. Recursive structures are detected and cause a fatal error. =head1 SEE ALSO The perlmonks site has a helpful introduction to when and why you might want to flatten a hash: http://www.perlmonks.org/index.pl?node_id=234186 =over 4 =item CGI::Expand Unflattens hashes using "." as a delimiter, similar to Template::Toolkit's behaviour. =item Tie::MultiDim This provides a tie interface to unflattening a data structure if you specify a "template" for the structure of the data. =item MLDBM This also provides a tie interface but reduces a nested structure to key-value form by serialising the values below the top level. =back =head1 VERSION $Id: Flatten.pm,v 1.19 2009/05/09 12:42:02 jamiel Exp $ =head1 AUTHOR John Alden E P Kent Ecpan _at_ bbc _dot_ co _dot_ ukE =head1 COPYRIGHT (c) BBC 2005. This program is free software; you can redistribute it and/or modify it under the GNU GPL. See the file COPYING in this distribution, or http://www.gnu.org/licenses/gpl.txt =cut Hash-Flatten-1.19/MANIFEST0000644016522100007720000000033711447132406016331 0ustar jamielengineers00000000000000Changes COPYING Makefile.PL MANIFEST MANIFEST.SKIP README lib/Hash/Flatten.pm t/hash_flatten.t t/overload.t t/data.lib t/pod.t t/pod_coverage.t META.yml Module meta-data (added by MakeMaker) Hash-Flatten-1.19/MANIFEST.SKIP0000644016522100007720000000017011447132362017072 0ustar jamielengineers00000000000000^blib ^bak ~$ (?:^|/)[Mm]akefile(?:\.old)?$ (?:^|/)pm_to_blib$ ^Hash-Flatten-\d+\.\d+\.(zip|tar\.gz|tgz)$ [Cc][Vv][Ss]/ Hash-Flatten-1.19/Makefile.PL0000644016522100007720000000072611447132362017155 0ustar jamielengineers00000000000000use ExtUtils::MakeMaker; WriteMakefile( NAME => 'Hash::Flatten', VERSION_FROM => 'lib/Hash/Flatten.pm', EXE_FILES => [], PREREQ_PM => { Test::Assertions => 0, Log::Trace => 0, }, ABSTRACT_FROM => 'lib/Hash/Flatten.pm', AUTHOR => 'British Broadcasting Corporation', ); Hash-Flatten-1.19/README0000644016522100007720000000102111447132364016052 0ustar jamielengineers00000000000000Hash::Flatten v1.19 (c) BBC 2004. This program is free software; you can redistribute it and/or modify it under the GNU GPL. See the file COPYING in this distribution, or http://www.gnu.org/licenses/gpl.txt QUICK START: Install Hash::Flatten by unpacking the tarball and running the following commands in the source directory: perl Makefile.PL make make test make install Then delete the source directory tree since it's no longer needed. run 'perldoc Hash::Flatten' to read the full documentation. Hash-Flatten-1.19/META.yml0000644016522100007720000000111311447132406016442 0ustar jamielengineers00000000000000--- #YAML:1.0 name: Hash-Flatten version: 1.19 abstract: flatten/unflatten complex data hashes author: - British Broadcasting Corporation license: unknown distribution_type: module configure_requires: ExtUtils::MakeMaker: 0 build_requires: ExtUtils::MakeMaker: 0 requires: Log::Trace: 0 Test::Assertions: 0 no_index: directory: - t - inc generated_by: ExtUtils::MakeMaker version 6.56 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4