从具有Perl CGI条件的数组中打印HTML表

时间:2016-10-13 13:17:00

标签: html perl cgi

我制作了一个脚本,它返回一个包含多行代码的数组:

  

DATA:VALUE:VALUE_MAX

我需要填写表格,如:

NAME |  Status
--------------------------
DATA |  OK/minor/warning...
.... |  .........
.... |  .........

使用VALUE和VALUE_MAX我计算给出状态的百分比。

这是我打印表格的代码:

my @i = my_status();

print <<END;
<div class="container">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
END
my $inc = 0;
while (@i) {
my @temp = split /:/, @i[$inc];
my $name = $temp[0];
my $percent = ($temp[1] * $temp[2] / 100);
my $status = undef;
if ($percent <= 24 ) {
print "<tr class='info'>";
$status = "Critical !";
}
elsif ($percent <= 49 ) {
print "<tr class='danger'>";
$status = "Danger !";
}
elsif ($percent <= 74 ) {
print "<tr class='warning'>";
$status = "Warning";
}
elsif ($percent <= 99 ) {
print "<tr class='active'>";
$status = "Minor";
}
elsif ($percent == 100 ) {
print "<tr class='success'>";
$status = "OK";
}
print "<td>$name</td>";
print "<td>$status</td>";
print "</tr>";
$inc++;
}
print <<END;
</tbody>
</table>
</div>
END

我的脚本“my_status”执行起来有点长,它充满了服务器请求......

但问题是,在HTML页面上,一切都是混乱,我得到了错误的价值,而且无限循环只打印“关键!”在状态colomns

我的脚本出了什么问题?

1 个答案:

答案 0 :(得分:2)

您在@i循环中迭代while。你的行

while (@i) {

表示只要@i为真,它就会保持在循环中。因为这是一个数组,这意味着只要@i中有项目,它就会保留在循环中。

您不会从循环内的@i中删除任何内容。没有shiftpop命令,您也不会覆盖@i。所以它将无限期地存在。你已经拥有了无限循环。

您想要的可能是foreach循环。那么你也不需要$inc。它会将@i中的每个元素放入$elem并运行循环。

foreach my $elem (@i) {
    my @temp    = split /:/, $elem;
    my $name    = $temp[0];
    my $percent = ( $temp[1] * $temp[2] / 100 );
    my $status  = undef;
    if ( $percent <= 24 ) {
        print "<tr class='info'>";
        $status = "Critical !";
    }
    elsif ( $percent <= 49 ) {
        print "<tr class='danger'>";
        $status = "Danger !";
    }
    elsif ( $percent <= 74 ) {
        print "<tr class='warning'>";
        $status = "Warning";
    }
    elsif ( $percent <= 99 ) {
        print "<tr class='active'>";
        $status = "Minor";
    }
    elsif ( $percent == 100 ) {
        print "<tr class='success'>";
        $status = "OK";
    }
    print "<td>$name</td>";
    print "<td>$status</td>";
    print "</tr>";
}

您可以阅读perlsyn starting from for loops中的循环。