简体   繁体   English

如何使用Perl将文件转换为HTML表?

[英]How can I convert a file to an HTML table using Perl?

I am trying to write a simple Perl CGI script that: 我正在尝试编写一个简单的Perl CGI脚本,该脚本是:

  • runs a CLI script 运行CLI脚本
  • reads the resulting .out file and converts the data in the file to an HTML table. 读取生成的.out文件,并将文件中的数据转换为HTML表。

Here is some sample data from the .out file: 这是.out文件中的一些示例数据:

 10.255.202.1   2472327594  1720341
 10.255.202.21   2161941840  1484352
  10.255.200.0   1642646268  1163742
 10.255.200.96   1489876452  1023546
 10.255.200.26   1289738466   927513
 10.255.202.18   1028316222   706959
 10.255.200.36    955477836   703926

Any help would be much appreciated. 任何帮助将非常感激。

The following is untested and probably needs a lot of polishing but it gives a rough idea: 以下内容未经测试,可能需要大量抛光,但是给出了一个大概的想法:

use CGI qw/:standard *table/;

print
  start_html('clicommand results'),
  start_table;

open(my $csvh, 'clicommand |');

while (<$csvh>) {
   print Tr(map { td($_) } split);
}

close($csvh);

print
  end_table,
  end_html;  

This doesn't directly answer your question, but is it possible to use AWK instead? 这不能直接回答您的问题,但是可以改用AWK吗? It shouldn't be too difficult to wrap the whole content, then each column entry with the appropriate html tags to create a basic table. 包装全部内容应该不太困难,然后使用适当的html标记为每个列条目创建一个基本表。

You'll very likely want to make the HTML prettier by using a CSS stylesheet or adding borders to the table, but here's a simple start. 您很可能希望通过使用CSS样式表或在表中添加边框来使HTML更漂亮,但这是一个简单的开始。

#!/usr/bin/perl

use strict;
use warnings;

my $output = `cat dat`;
my @lines  = split /\n/, $output;

my @data;
foreach my $line (@lines) {
    chomp $line;
    my @d = split /\s+/, $line;
    push @data, \@d;
}

print <<HEADER;
<html>
<table>
HEADER

foreach my $d (@data) {
    print "\t", "<tr>";
    print map { "<td>$_</td>" } @$d;
    print "</tr>", "\n";
}

print <<FOOTER;
</table>
</html>
FOOTER

This makes the following output: 这将产生以下输出:

<html>
<table>
        <tr><td>10.255.202.1</td><td>2472327594</td><td>1720341</td></tr>
        <tr><td>10.255.202.21</td><td>2161941840</td><td>1484352</td></tr>
        <tr><td>10.255.200.0</td><td>1642646268</td><td>1163742</td></tr>
        <tr><td>10.255.200.96</td><td>1489876452</td><td>1023546</td></tr>
        <tr><td>10.255.200.26</td><td>1289738466</td><td>927513</td></tr>
        <tr><td>10.255.202.18</td><td>1028316222</td><td>706959</td></tr>
        <tr><td>10.255.200.36</td><td>955477836</td><td>703926</td></tr>
</table>
</html>

To understand how to modify the look of your HTML tables, the w3schools website entry on the table tag is a good start. 要了解如何修改HTML表格的外观, 表格标记上的w3schools网站条目是一个不错的开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM