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

Hi,
I have these three sets of parameters. And I want to run these group of parameters automatically.
#Parameters Group 1: my $x = 1; my $y = 2; my $z = 3; #Parameters Group 2: my $x = 3; my $y = 4; my $z = 5; #Parameters Group 3: my $x = 1; my $y = 1; my $z = 1;
How can I construct the code with the params setting (they are fixed) as above and the "main" subroutine below:
sub main { my ($x,$y,$z) = @_; my %final_hash; # Something like this??? # I'm totally lost here # $final_hash{$paramgroup} = add_them($x,$y,$z); return %final_hash; } sub add_them { my ($x,$y,$z) = @_; return ($x+$y+$z); }
Such that in the end it simply gives:
$result = { 'ParamGroup1' => 6, # 1+2+3 'ParamGroup2' => 12, # 3+4+5 'ParamGroup3' => 3, # 1+1+1 };
And my last question is. Can we avoid using "main subroutine"? Will it be a better approach?

Thanks so much beforehand.
Regards,
Edward

Replies are listed 'Best First'.
Re: Running Code with Multiple Sets of Parameters Automatically
by Zaxo (Archbishop) on Jul 25, 2005 at 03:10 UTC

    You can place your groups of data in an array. Your problem is in having several variables all the same name.

    my @param_groups = ( { x => 1, y => 2, z => 3 }, { x => 3, y => 4, z => 5 }, { x => 1, y => 1, z => 1 }, ); my ($count, %result) = 1; for (@param_groups) { $result{'ParamGroup'.$count++} = add_them(@{$_}{qw/x y z/}); }

    After Compline,
    Zaxo

Re: Running a Code with Multiple Sets of Parameters Automatically
by GrandFather (Saint) on Jul 25, 2005 at 03:11 UTC

    So you want a HoA (hash of arrays)? Something like this:

    my %Params = ( 'ParamGroup1' => [1, 2, 3], 'ParamGroup2' => [3, 4, 5], 'ParamGroup3' => [1, 1, 1] );

    Perl is Huffman encoded by design.
      Which means that the OP can use map:
      my %all_results = map { $_ => add_them(@{$Params{$_}}) } sort keys %Pa +rams;
      I put sort just to preserve the exact order of calls to add_them, just in case some state is preserved inside the function itself.

      Flavio
      perl -ple'$_=reverse' <<<ti.xittelop@oivalf

      Don't fool yourself.
Re: Running a Code with Multiple Sets of Parameters Automatically
by spiritway (Vicar) on Jul 25, 2005 at 19:39 UTC

    I suggest that you put the parameters into a file. Then all you'd have to do is use a while (<FILE>) construct to get the parameters into your program.