Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: Storing multiple arguments in a data structure that allows for future expansion

by jbert (Priest)
on May 02, 2007 at 09:07 UTC ( #613140=note: print w/replies, xml ) Need Help??

in reply to Storing multiple arguments in a data structure that allows for future expansion

I'm not sure this is the simplest way, but the problem suggested recursion to me. The code below demonstrates what I think you want to achieve. It's a 'first class functions' approach and uses the ability of a closure (anonymous subroutine) to capture information.

My starting point is where I think you are already - you have a hash whose keys are the options and whose values are array references containing the multiple-choice values. If you don't have that already, then simply go through the values of your options hash, replacing each value with [ split(/,/, $value) ] or similar.

I then pass the multi-option hash and the function I was executed to the 'run_all_perms' function. This then plucks one key and list-of-values from the options hash.

If we have more options to process, it recurses once for each value in the list, but we wrap the 'work' function in in a closure which installs the particular value in a hashref passed to the work function.

If we don't have any more options to process, it can actually call the passed in work function, passing in the particular value.

Here's the code:

#!/usr/bin/perl use warnings; use strict; use Data::Dumper qw/Dumper/; my %opts = ( a => [qw/1 2 3/], b => [qw/4 5 6/], c => [qw/foo bar baz/], ); # The work function should expect a hashref containing the values # for this run my $work = sub { my $hr = shift; print "A $hr->{a} B $hr->{b} C $hr->{c}\n"; }; run_all_perms(\%opts, $work); exit 0; sub run_all_perms { my $orig_opts = shift; my $work = shift; my %multi_opts = %$orig_opts; my @keys = sort keys %multi_opts; my $key = $keys[0]; # We don't want to pass this key on my $vals = delete $multi_opts{$key}; foreach my $val (@$vals) { if (keys %multi_opts) { # We have more perms to do my $new_work = sub { my $hr = shift; # Capture this arg in the hashref $hr->{$key} = $val; # Run the previous work function with the accumulated +args $work->($hr); }; # Recurse with our accumulating work function run_all_perms(\%multi_opts, $new_work); } else { # We've captured all the args we need, let's go $work->({$key => $val}); } } }

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://613140]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2021-07-23 19:54 GMT
Find Nodes?
    Voting Booth?

    No recent polls found