[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] How to store hash of hashes



Hi Baron,

First, I would suggest using a DBM file to store the top-level hash.  Then just use join/split to store the sub-hashes as values in the DBM file.

If that approach doesn't appeal to you, I would suggest doing something using map, join, and split to convert the entire structure to a string and back again.  For example, you might do:

-------

my %subscribers = (    
                   "name\@company.com" =>
                   {
                       "first_name" => "John",
                       "last_name"  => "Doe",
                       "checkbox_1" => "1",
                       "checkbox_2" => "0",
                   },    ## Syntax corrected from your example.
                   "name2\@aCompany.com" =>
                   {
                       "first_name"   => "Jane",
                       "last_name"    => "Smith",
                       "checkbox_1"   => "0",
                       "checkbox_2"   => "1",
                   },
                   );

## Make the structure into a string:
my $Stored = join ("\001", map {($_, join("\t", %{$subscribers{$_}}))} keys (%subscribers));

## Convert the string back to an in-memory structure:
my %Restored = split(/\001/, $Stored); undef $Stored;
foreach (keys(%Restored)) {$Restored{$_} = {split("\t", $Restored{$_})}};

--------

The above code of course assumes that none of the strings contain tabs or ASCII 01.

You could obviously use any two delimiters you choose as long as you can guarantee that they will not appear in your data.

Also, the above code is somewhat memory-inefficient in the case of very large hashes (see my earlier admonition about usind DBM files).

Also, unless I am mistaken, this is a general Perl question and might have been better directed to a perl-related list or group than a MacPerl group.

Hope this helps!

-c


------------------------------------------------------------------------
Chris Thorman                           ct@if.net
If.Net, Inc.                            (415) 392-6244 voice
870 Market Street                       (415) 392-6245 fax
San Francisco, CA 94102                 http://if.net
------------------------------------------------------------------------