Search code examples
htmlperltextmarkdown

convert markdown text to html table using perl


I'm trying to convert a Markdown text to HTML table with Perl modules. I tried to use Text::Markdown, but it didn't work.

I also tried to use Markdown::Table and follow the documentation: https://metacpan.org/pod/Markdown::Table, but same thing no result.

Here is my code:

use Markdown::Table;

my $markdown = q~
| Id | Name | Role |
+---+---+---+
| 1 | John Smith | Testrole |
| 2 | Jane Smith | Admin |
~;
 
my @tables = Markdown::Table->parse($markdown);
                        
use Data::Dumper;
Core::Global::Logger::debug(Dumper( $tables[0]->get_table ) );

Output: enter image description here

can anyone help about that please ?


Solution

  • Use Text::MultiMarkdown the original Markdown doesn't support tables. And Text::Markdown only supports the orignal syntax.

    Text::MultiMarkdown has additional features.

    Additional you have to change the table format.

    use v5.10;
    use Text::MultiMarkdown qw(markdown);
    
    my $text = q[
    | Id | Name | Role |
    |---|---|---|
    | 1 | John Smith | Testrole |
    | 2 | Jane Smith | Admin |
    ];
    
    # Replace any CRLF/LF line-endings to the native Line-Ending used by Perl
    $text =~ s/\R/\n/g;
    
    my $html = markdown($text);
    
    printf "%s\n", $html;
    

    will produce

    <table>
    <col />
    <col />
    <col />
    <thead>
    <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Role</th>
    </tr>
    </thead>
    <tbody>
    <tr>
            <td>1</td>
            <td>John Smith</td>
            <td>Testrole</td>
    </tr>
    <tr>
            <td>2</td>
            <td>Jane Smith</td>
            <td>Admin</td>
    </tr>
    </tbody>
    </table>