How can I convert a file to HTML table using Perl?

I am trying to write a simple Perl CGI script that:

  • runs the CLI script
  • reads the resulting .out file and converts the data to the file into an HTML table.

Here are some examples of data from the .out file:

 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.

+2


a source to share


3 answers


The following is untested and probably requires 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;  

      

+1


a source


This doesn't directly answer your question, but is it possible to use AWK? It shouldn't be too hard to wrap all the content and then each column record with the appropriate html tags to create a base table.



0


a source


You will most likely want to make your HTML prettier by using a CSS stylesheet or adding borders to the table, but here's an easy start.

#!/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 conclusion:

<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 change the look of your HTML tables, a good start to the w3schools page in the table tag .

0


a source







All Articles