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

Hi Monks,

I need to generate combinations of values and populate it in a hash of hashes. Say Eg:

f1 = (1,2) f2 = (3,4,5) f3 = (6,7)

I get 12 unique combinations out of these(2*3*2). Like:

f1 f2 f3

1 3 6

1 3 7

1 4 6

1 4 7

.

.

2 3 6

.

.

2 5 7

All these combinations should be stored as values under each field key(f1 or f2 or f3). But the problem is in generation of combinations as THE NO. OF FIELDS IS VARIABLE!! All fields and their values are stored in array. I need to construct a table of the above combinations. Plz help

for(1 to n of f1)

{

for(1 to n of f2)

{

for(1 to n of f3)

{

store f11 f21 f31 to f3last element

}

}

}

this can be used provided we know the actual field count. But what can be done for occurance of random number of fields with their respective values??

Replies are listed 'Best First'.
Re: Populating Hash of hashes
by moritz (Cardinal) on Jul 27, 2009 at 12:05 UTC
    You can create $n nested loops with Algorithm::Loop.

    If you want even less, work the module Set::CrossProduct does exactly what you want, wrapped in a neat iterator.

    Another option is to the built-in function glob:

    $ perl -wle 'print for glob "{1,2}{3,4,5}{6,7}"' 136 137 146 147 156 157 236 237 246 247 256 257
      Thanks Moritz It really helped!! I am planning to use glob
Re: Populating Hash of hashes
by ig (Vicar) on Jul 28, 2009 at 03:17 UTC

    If you have a variable number of fields as a hash with variable number of elements, you can iterate over the list, processing the fields one at a time.

    You might find an introduction to programming helpful. For self study, there are pointers to many resources for learning Perl programming in Where and how to start learning Perl.