为什么 CGI 不显示输入字段的标签

Why is CGI not showing labels for input fields

我是 perl CGI 的新手,想为用户输入创建一个 CGI 表单。问题是代码没有输出字段名称。

这是代码:

#!/usr/bin/perl -T

use strict;
use warnings;
use diagnostics;
use CGI;
my $cgi = CGI->new;
print $cgi->header(),
$cgi->start_html(
    -title => "my form",
),
$cgi->p(scalar localtime),

$cgi->p("welcome to myform"),
$cgi->start_form({
    -action =>"",
    -method =>"",
});
print $cgi->textfield({
    -label => "Username :",
    -type => 'text',
    -size=>30,});

$cgi->end_form(),

$cgi->end_html();

在上述情况下,我希望 html 输出显示用户名的标签。

CGI 模块不支持 textfield 元素的 -label 属性。相反,您必须将它包含在单独的 <label> 元素中,例如

print $cgi->label(
  'Username :',
  $cgi->textfield({
    -type => 'text',
    -size=>30,})
);

但也请注意 HTML 生成函数不应再使用 the module's own documentation 中的警告

All HTML generation functions within CGI.pm are no longer being maintained. Any issues, bugs, or patches will be rejected unless they relate to fundamentally broken page rendering.

The rationale for this is that the HTML generation functions of CGI.pm are an obfuscation at best and a maintenance nightmare at worst. You should be using a template engine for better separation of concerns. See CGI::Alternatives for an example of using CGI.pm with the Template::Toolkit module.