You'd have better luck generalizing that if the data was in an AoA. The use of numbering for keys is a clue that this is true. Your desired output is dependent on the ordering of the keys, which a hash does not provide naturally.
Writing the data as an AoA is just as simple:
There is a fine trick for producing combinations like you want. It uses glob. The string "{a,b}-{c,d}", fed to glob, will generate the same list as qw/a-c a-d b-c b-d/. Here's how to generate your strings with that:#!/usr/bin/perl my $data = [ [ 1, 2, 3, 4 ], [ 10, 20, 30 ], [ 100, 200, 300 ], ];
The glob pattern $gpat is '{1,2,3,4}\ -\ {10,20,30}\ -\ {100,200,300}'. Results follow:my $gpat = do { local $" = '}\ -\ {'; qq({@{[ map { local $" = ','; "@$_"; } @$data ]}}); }; print $gpat, $/; { local $, = "\n"; print glob $gpat; print $/; }
__END__ {1,2,3,4}\ -\ {10,20,30}\ -\ {100,200,300} 1 - 10 - 100 1 - 10 - 200 1 - 10 - 300 1 - 20 - 100 1 - 20 - 200 1 - 20 - 300 1 - 30 - 100 1 - 30 - 200 1 - 30 - 300 2 - 10 - 100 2 - 10 - 200 2 - 10 - 300 2 - 20 - 100 2 - 20 - 200 2 - 20 - 300 2 - 30 - 100 2 - 30 - 200 2 - 30 - 300 3 - 10 - 100 3 - 10 - 200 3 - 10 - 300 3 - 20 - 100 3 - 20 - 200 3 - 20 - 300 3 - 30 - 100 3 - 30 - 200 3 - 30 - 300 4 - 10 - 100 4 - 10 - 200 4 - 10 - 300 4 - 20 - 100 4 - 20 - 200 4 - 20 - 300 4 - 30 - 100 4 - 30 - 200 4 - 30 - 300
The do block I use for generating the glob pattern looks forbidding, but is not so bad if you break it down from the inside out. It's just two nested cases of setting $" to control what joins quoted arrays, and then supplying a quoted array to each. The nastiest bits are the "extra" curlies which are really quoted text. That construction could be done in several steps with temporary variables and join, if maintainance is an issue.
After Compline,
Zaxo
In reply to Re: Creating a Dynamic Nested Loops for HoA
by Zaxo
in thread Creating a Dynamic Nested Loops for HoA
by monkfan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |