neversaint has asked for the wisdom of the Perl Monks concerning the following question:

Dear Masters,
Just simple question. Given this array
my @array = qw (foo bar qux);
How can I generate/initialize a Hash of Hash of Array like this with Map:
my $VAR1 = { 'foo' => { 'foo' => [], 'bar' => [], 'qux' => [] }, 'bar' => { 'foo' => [], 'bar' => [], 'qux' => [] }, 'qux' => { 'foo' => [], 'bar' => [], 'qux' => [] }, };
I can do it with double foreach but since in the actual situation the array is very large (ten thousand elements ore more) and I need it to be super fast. I suppose 'map' is the answer?

---
neversaint and everlastingly indebted.......

Replies are listed 'Best First'.
Re: Initializing HoHoA with Map
by BrowserUk (Patriarch) on Aug 01, 2006 at 08:36 UTC

    If your initial array is already "huge", then you will likely run out of ram long before you manage to generate your HoHoA.

    If your array has

    1. 1000 elements, creating this HoHoA will require ~ 100 MB;
    2. for 2000, ~ 400 MB
    3. for 4000, ~ 1.2 GB

    Which approximates to O(n2)* memory consumption, so depending upon what you classify as a huge array, you are likely to run out of memory long before performance will ever be a concern.

    *Update: 2 not 3. Thanks radion.

    In most cases, once you get beyond fairly small sized arrays, for/foreach will outperform map as the latter needs to allocate substantial amounts of memory in order to build a temporary list to accomodate the array, whereas the former iterates the array without requiring to allocate extra space.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Initializing HoHoA with Map
by Sidhekin (Priest) on Aug 01, 2006 at 08:11 UTC

    I don't know if map will be any faster, but ...

    my $VAR1 = { map { $_ => { map { $_ => [] } @array } } @array };

    print "Just another Perl ${\(trickster and hacker)},"
    The Sidhekin proves Sidhe did it!