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

I am getting several variables (some hidden) from a form that I am trying to process with CGI. The problem is that some names are to some point unknown, they are of the kind $user-$anothervariable, their values are numbers. More in detail:
$names[0] is the username $names[1] holds the path to the html file where the
redirection is going to occur to after the processing of data
$names[2], $names[3], ..., (undetermined amount) hold
numbers that will be processed.  @names[2] and on are something like $username-$anothervariable. I need to be able to retrieve the values of these variables whose names contain the username+something, but I am lost at that. Still, if it is dome with a foreach loop, I will need to be able to send out of the loop the number values, because I need to do some tricks with them.

Replies are listed 'Best First'.
Re: Getting back values of an array of names reurned by CGI when the names are variables
by Happy-the-monk (Canon) on Oct 24, 2004 at 22:30 UTC

    This smells like bad design.
    However, provided it is CGI, you can easily do:

    # If I got you right and the variable in question was multivalue # (as you represented it with a Perl array): my ( $username, $path, @names ) = $cgi->param("names"); # to geht what you need for the following: my @value; # will contain the values. foreach my $i ( 0 .. $#names ) { my $combined_name = $username . "-" . $names[$i]; # build the key $value[$i] = $cgi->param("$combined_name"); # fetch the valu +e }

    Update: Code rewritten as foreach loop

    Cheerio, Sören

Re: Getting back values of an array of names reurned by CGI when the names are variables
by jeffa (Bishop) on Oct 25, 2004 at 15:00 UTC

    Here is how i would handle it, if i read you correctly. Preface your hidden variables with user_ and then grep those values from CGI::param() like so:

    use strict; use warnings; use Data::Dumper; use CGI qw(param); my %user = map {$_ => param($_)} grep /^user_/, param(); print Dumper \%user;
    You can test this snippet on a command line like so:
    ./foo.pl "user_foo=bar&user_bar=baz&something=else"

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)