http://qs1969.pair.com?node_id=541925

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

I know this must have been asked before but I don't know what to search for to find it.

I am using CGI and I have a form with 25 questions. The fields are q1, q2, q3, q3.... q25. If it makes any difference, these are radio buttons and they can only select the one value.

What is the easiest way to have all this data without me having to manually..

my $q1 = param('q1'); my $q25 = param('q25');

Replies are listed 'Best First'.
Re: simplifying a CGI param request
by brian_d_foy (Abbot) on Apr 07, 2006 at 17:24 UTC

    You don't need to store these in separate variables to use them. Just access the right thing with param when you need it:

    foreach my $number ( 1 .. 25 ) { my $value = param( "q$number"); print "q$number: $value\n"; # or, without $value # printf "q%d: %s\n", $number, param( "q$number" ); }

    If you really must import these, you could use an array (since you know they are ordered). You can fill in the element with index 0 with undef just to keep the numbers straight.

    my @array = ( undef, map { scalar param("q$_") } 1 .. 25 );

    If you really wanted these things in a variable, you can use the CGI::import function to do it all at once. It ends up creating package variables though, so it's usually not a good idea.

    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review
Re: simplifying a CGI param request
by sulfericacid (Deacon) on Apr 07, 2006 at 17:09 UTC
    my $cnt = 0; my %params; for (1 .. 25) { $cnt++; $params{"q$cnt"} = param("q$cnt"); }
    Untested but this will either work or give you the right idea.


    "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

    sulfericacid
      hashes don't keep them in the order I need. How would I sort them to print out q1, q2, q3 etc in order in a foreach loop?
        You'd take his for loop and instead of putting the stuff in a hash you'd just do something with the number right then and there!
        for (1 .. 25) { my $value = param("q$_"); print "Value #$_ = $value\n"; }

        Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
        How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: simplifying a CGI param request
by explorer (Chaplain) on Apr 08, 2006 at 09:47 UTC