user329313
user329313

Reputation: 29

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

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

Here is some sample 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.

Upvotes: 2

Views: 1810

Answers (3)

James Thompson
James Thompson

Reputation: 48162

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.

#!/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.

Upvotes: 0

reinierpost
reinierpost

Reputation: 8591

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;  

Upvotes: 1

Ryan P.
Ryan P.

Reputation: 845

This doesn't directly answer your question, but is it possible to use AWK instead? 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.

Upvotes: 0

Related Questions