我正在尝试根据使用CGI的迭代打印表单中的字段。是否可以在CGI打印语句中嵌套for循环?我一直在for循环线上得到语法错误......
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'),
),
),
答案 0 :(得分:2)
没有。相反,您应该将所有项目推送到数组(在创建父元素之前),然后将数组作为参数传递。
答案 1 :(得分:0)
有点儿。您可以使用for
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'),
),
),
);
尽管如此,预计算内部部件可能更容易。
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 ) );
如果您确实希望for
位于中间,可以使用startXXX
和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();
最后,map
整齐地结合了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'),
),
),
);