Search code examples
cgi

How to create table for my perl output using perl cgi?



Here is my code and output i was unable to create the different row for my each line using perl?

Here is my code:

   use strict;
    use warnings;
    use CGI;
    open(my $file1,"as.txt");
    my $firstline=<$file1>;
    $firstline=~s/.*=//g;
    my @words=split /,/,$firstline;
    my $finalline=join("\n",@words);
    close $file1;
    print "Content-type:text/html\n\n"
    print<<"EOF";
    <html><body>
    <table style="width:100%">
    <tr>
    <th>UserName</th>
    <th>Access</th>
    </tr>
    <tr>
    <td>$finalline</td>
    <td>
    <input type="checkbox" value="check2" mulitple checked>Read
    <input type="checkbox" value="check2" mulitple>Write
    <input type="checkbox" value="check2" mulitple>Owner
    </td>
    </tr>
    </table></body></html>
    EOF

MY OUTPUT FOR PERL (I.E $finalline) sankar morien3

i got the following table as my output in table format:

UserName    Access
sankar morien3 Read Write Owner

Expected output:

UserName    Access
sankar  Read Write Owner
morien3 Read Write Owner

Input file:(i.e as.txt)

cskTeam = sankar, mobrien3
[csk:/]

* = r
@cskTeam = rw

Solution

  • You must know about how HTML layout will work.

    Even your code won't give your expected result in terminal.

    In html \n not make sense, <br> it is for new line in html. But this logic also won't work in your code.

    You are joining the array with \n, then printing the data it will execute the comment line by line what you have mentioned.

    First you have printing the $finalline variable so it result is

    sankar \n morien3  
    

    \n will not consider in html. Storing in one cell as per <td>

    Then you are creating the another cell which holds the permission detail.

    Finally your code should be as follows.

    #!/usr/bin/perl
    use warnings;
    use strict;
    use CGI;
    
    use CGI::Carp qw(fatalsToBrowser);
    
    print "Content-Type: text/html \n\n";
    
    
    open my $file1,"<","as.txt";
    my $firstline=<$file1>;
    $firstline=~s/.*=//g;
    my @words=split /,/,$firstline;
    close $file1;
    
    
    print<<"EOF";
    <html><body>
    <table style="width:50%; ">
    <tr>
    <th style="text-align:left">UserName</th>
    <th style="text-align:left">Access</th>
    </tr>
    EOF
    foreach (@words)
    {
    print <<EOF;
    <tr>
    <td>$_</td>
    <td>
    <input type="checkbox" value="check2" mulitple checked>Read
    <input type="checkbox" value="check2" mulitple>Write
    <input type="checkbox" value="check2" mulitple>Owner
    </td>
    </tr>
    EOF
    }
    print <<EOF;
    </table></body></html>
    EOF