On 2012-02-26 23:55, Rob Dixon wrote:
> On 27/02/2012 02:30, Steve Bertrand wrote:
>> I know this isn't a beginner's question, but I know there are geniuses
>> here. Is there a way to simplify this within Perl?
>
> Hi Steve
>
> Much of the complexity comes from working with the nested data
> structure. Writing a subroutine that takes just a set of the 'values'
> arrays cleans things up a lot. Take a look at the program below.
In my mind, I knew that map() had to fit in someplace, but by the time I
thought about map, I was ready to ask for help instead of performing the
Schwartzian Transform physically on my keyboard :)
This is another great piece of code I (and others) can study. I'm
leaving it below. Thank you Rob!
> use strict;
> use warnings;
>
> my $attributes = [
> { type => 'colors', values => [qw/red green blue/] },
> { type => 'sizes', values => [qw/small large/] },
> { type => 'shades', values => [qw/light dark/] },
> ];
>
> print "$_\n" foreach combos(map $_->{values}, @$attributes);
>
> sub combos {
>
> my $first = shift;
>
> return @$first unless @_;
>
> my @combinations;
>
> foreach my $beg (@$first) {
> foreach my $end (combos(@_)) {
> push @combinations, "$beg $end";
> }
> }
>
> return @combinations;
> }
Thread Previous
|
Thread Next