Jan Eden wrote: > > Hi all, > > there must be a better way to do this. My task is to create a multiple choice > test in HTML. First, I print the question (frage): > ---- > my $query = "SELECT frage_id, frage_text, antwort_text_1, antwort_text_2, > antwort_text_3, antwort_text_4, antwort_text_5 FROM fragen"; > my $sth = $dbh->prepare($query); > $sth->execute(); > print qq{<form action="show_multi.pl" method="post" > enctype="application/x-www-form-urlencoded" > accept-charset="utf-8"><table>}; > my $counter; > while (my ($frage_id, $frage_text, $antwort_text_1, $antwort_text_2, > $antwort_text_3, $antwort_text_4, $antwort_text_5) > = $sth->fetchrow_array) { > $counter++; > print qq{ > <tr> > <td> > Frage $counter: > </td> > <td> > $frage_text > </td> > </tr>}; > ----- > > Next, the possible answers should be printed Now instead of calling each > answer's variable explicitly, I'd like to use a loop. > > ----- > foreach my $count (1..5) { > $antwort = "antwort_text_$count"; > print qq{<tr> > <td> > <input type="checkbox" name="${frage_id}_antwort_$count"> > </td> > <td> > ${"$antwort"} > </td> > </tr> > }; > } > } > print qq{</table><input type="hidden" name="mode" value="result" /> > <input type="submit" name="Absenden" value="Absenden" /></form>}; > $sth->finish(); > -----
Hi Jan. > $antwort is declared as an our variable and it holds the string > "antwort_text_1", "antwort_text_2" etc., but the dereferencing never works. An > empty string is printed. The string "1_antwort_1" as the name of an input > field is generated correctly, of course. $antwort doesn't need to be a global variable, but $antwort_text_1 .. 5 do, as symbolic references don't work on lexical variables. $count = 1; $antwort = "antwort_text_$count"; print ${$antwort}; prints $main::antwort_text_1 (or whatever the current package is). perldoc perlref says: Only package variables (globals, even if localized) are visible to symbolic references. Lexical variables (declared with my()) aren't in a symbol table, and thus are invisible to this mechanism. > But even if I got the dereferencing to work, this solution looks suboptimal. > Could anyone suggest a way to loop through the different answers without using > /no strict "refs"/, i.e. without making use of symbolic references at all? How about this: while (my ($frage_id, $frage_text, @antwort) = $sth->fetchrow_array) { $counter++; print qq{ <tr> <td> Frage $counter: </td> <td> $frage_text </td> </tr> }; my $count; foreach my $antwort (@antwort) { $count++; print qq{ <tr> <td> <input type="checkbox" name="$frage_id_antwort_$count"> </td> <td> $antwort </td> </tr> }; } } HTH, Rob (BTW Jan I know I owe you an email. I'm getting to it!) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>