printing using a for loop in cgi
I'm attempting to print fields in a form depending on the iteration using CGI. Is it possible to nest a for loop within a CG开发者_StackOverflowI print statement like so? I keep getting a syntax error on the for loop line...
print $survey->Tr(
$survey-td(
$survey->startform(name=>'survey', method => 'POST', action => 'survey.cgi'),
for ($i=0; $i < $size; $i++){
$survey->hidden(name=>"q$i", value => "currentQ[q$i]"),
$survey->submit(name=>'direction', value =>'Previous'),
$survey->endform(),
}
$survey->startform(name=>'survey', method=>'POST', action=>'survey.pl.cgi'),
$survey->submit(name=>'direction', value =>'Next'),
),
),
No. Instead you should push all the items on to an array (in advance of creating the parent element) and then pass the array as the argument.
Kinda. You can embed a for
using do
:
print $survey->tr(
$survey->td(
do {
my @forms;
for my $i (0..$size-1) {
push @forms, $survey->form(
{ name=>'survey', method => 'POST', action => 'survey.cgi' },
$survey->hidden(name=>"q$_", value => "currentQ[q$_]"),
$survey->submit(name=>'direction', value =>'Previous'),
);
}
@forms
},
$survey->form(
{ name=>'survey', method=>'POST', action=>'survey.pl.cgi' },
$survey->submit(name=>'direction', value =>'Next'),
),
),
);
It's probably easier to precompute the inner parts, though.
my @forms;
for my $i (0..$size-1) {
push @forms, $survey->form(
{ name=>'survey', method => 'POST', action => 'survey.cgi' },
$survey->hidden(name=>"q$i", value => "currentQ[q$i]"),
$survey->submit(name=>'direction', value =>'Previous'),
);
}
push @forms, $survey->form(
{ name=>'survey', method=>'POST', action=>'survey.pl.cgi' },
$survey->submit(name=>'direction', value =>'Next'),
);
print $survey->tr( $survey->td( @forms ) );
If you really do want to have for
in the middle, you could use startXXX
and endXXX
.
print $survey->starttr();
print $survey->starttd();
for my $i (0..$size-1) {
print $survey->form(
{ name=>'survey', method => 'POST', action => 'survey.cgi' },
$survey->hidden(name=>"q$i", value => "currentQ[q$i]"),
$survey->submit(name=>'direction', value =>'Previous'),
);
}
print $survey->form(
{ name=>'survey', method=>'POST', action=>'survey.pl.cgi' },
$survey->submit(name=>'direction', value =>'Next'),
);
print $survey->endtd();
print $survey->endtr();
Finally, map
neatly combines do
for
.
print $survey->tr(
$survey->td(
( map {
$survey->form(
{ name=>'survey', method => 'POST', action => 'survey.cgi' },
$survey->hidden(name=>"q$_", value => "currentQ[q$_]"),
$survey->submit(name=>'direction', value =>'Previous'),
);
} 0..$size-1 ),
$survey->form(
{ name=>'survey', method=>'POST', action=>'survey.pl.cgi' },
$survey->submit(name=>'direction', value =>'Next'),
),
),
);
精彩评论