Home > Software design >  How to create HTML tables dynamically using Perl?
How to create HTML tables dynamically using Perl?

Time:06-24

I am working on a project where I need to access CSV file form a web URL. I am able access the file and print the content from CSV file in the terminal, but I'm unable to produce HTML table (then I'll later send email using MIME).

Here is my code - I need complete CSV file as HTML table delivered to my email.

#!/usr/bin/perl
use strict;
use warnings;

use LWP::Simple;
use POSIX qw(strftime);
use MIME::Lite;
use Getopt::Long;

my $to="pankajdustbin\@gmail.com";
my $from="pankajdustbin\@gmail.com";
$subject="CSV File";

my $content = `curl -s "https:csvfile.com"`;

@output = split(/\n/,$content);

foreach my $line (@output) {
    my ($col1, $col2, $col3, $col4, $col5, $col6) = split(/,/, $line);
    #print "\n$col1, $col2, $col3, $col4, $col5, $col6\n";

    $message = "<tr> <td>$col1</td> <td>$col2</td> <td>$col3</td> <td>$col4</td> <td>$col5</td> <td>$col6</td></tr>";
}

my $msg=MIME::Lite->new(
        From => $from,
        To => $to,
        Subject => $subject,
        Data => $message
        );

$msg->attr('content-type' => 'text/html');
#MIME::Lite->send("smtp");
$msg->send;

With this code, the HTML table contains only the last row of the CSV. Can someone help me how I should do?

CSV has around 100 rows, and the sample output that I see in terminal as below:

1.2.3.4  03-04-2022.  03-08-2022. Red.  1%.  Positive
5.2.3.4  03-05-2022.  04-08-2022. Blue.  1%.  Neutral
and so on...

CodePudding user response:

The problem is that you overwrite the contents of the $message variable each time through the foreach loop. This means that $message will only have the last value that you assign to it.

You could append to the contents of the variable using the .= operator:

my $message;
foreach my $line (@output) {
    my ($col1, $col2, $col3, $col4, $col5, $col6) = split(/,/, $line);
    $message .= "<tr> <td>$col1</td> <td>$col2</td> <td>$col3</td> <td>$col4</td> <td>$col5</td> <td>$col6</td></tr>";
}
  • Related