Banging my head over this all day. Basically, I have a list of products (an arbitrary list stored in a database), which I pull out into an array called @products. Each product can have a number of attributes, as shown below. I made a simple loop to go through colors and sizes and print exactly what I'm look for in terms of output. Unfortunately, the number of attributes is also arbitrary, so there could be sizes, colors, styles, flair, etc. So I need to come up with a way to print the list of products with every available option dynamically.
Here is the simple code that prints what I want.
#!/usr/bin/perl
use strict;
my @products = ('tshirt', 'pants', 'sweatshirt');
my @sizes = ('small', 'medium', 'large'),
my @colors = ('red', 'green', 'blue');
foreach my $product (@products) {
foreach my $size (@sizes) {
foreach my $color (@colors) {
print "$product $size $color\n";
}
}
}
Here is the output I want
tshirt small red
tshirt small green
tshirt small blue
tshirt medium red
tshirt medium green
tshirt medium blue
tshirt large red
tshirt large green
tshirt large blue
pants small red
pants small green
pants small blue
pants medium red
pants medium green
pants medium blue
pants large red
pants large green
pants large blue
sweatshirt small red
sweatshirt small green
sweatshirt small blue
sweatshirt medium red
sweatshirt medium green
sweatshirt medium blue
sweatshirt large red
sweatshirt large green
sweatshirt large blue
Here is an example (%options) of the structure I will be building dynamically from the database. I am simply stuck on how to get from this structure to the output listed above! Any help would be greatly appreciated. Please note that the hard part seems to be the fact that the %options has can grow and shrink!
my @products = ('tshirt', 'pants', 'sweatshirt');
my %options = (
'sizes' => ['small', 'medium', 'large'],
'colors' => ['red', 'green', 'blue']
);
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.