App-TextTableUtils

 view release on metacpan or  search on metacpan

script/csv2mdtable  view on Meta::CPAN

#!perl

use 5.010001;
use strict;
use warnings;

our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
our $DATE = '2023-12-03'; # DATE
our $DIST = 'App-TextTableUtils'; # DIST
our $VERSION = '0.010'; # VERSION

my ($ifmt, $ofmt) = $0 =~ /(\w+)2(\w+)\z/ or die "Please call me as <foo>2<bar> (not $0)";

# parse options
my %Opts;
{
    require Getopt::Long;
    Getopt::Long::Configure("bundling", "no_ignore_case", "permute", "no_getopt_compat");
    Getopt::Long::GetOptions(
        "backend|b=s" => \$Opts{backend},
        "transpose|t" => \$Opts{transpose},
        "csv-sep|s=s" => \$Opts{csv_sep},
        "csv-quote|q=s" => \$Opts{csv_quote},
        "csv-escape|e=s" => \$Opts{csv_escape},
        "csv-loose|l" => \$Opts{csv_loose}
    ) or die "$0: Error in getting options, bailing out\n";
}

# get input handle
my $fh;
{
    if (@ARGV == 1) {
        open $fh, "<:encoding(utf8)", $ARGV[0] or die "Can't open $ARGV[0]: $!";
    } elsif (!@ARGV) {
        binmode(STDIN, ":encoding(utf8)");
        $fh = \*STDIN;
    } else {
        die "Usage: $0 <filename>\n";
    }
}

my $rows;
# parse input into rows
{
    if ($ifmt eq 'csv') {
        require Text::CSV;
        my $csv = Text::CSV->new({ binary => 1 })
            or die "Cannot use CSV: ".Text::CSV->error_diag;
        if ($Opts{csv_sep}) {
            $csv->sep_char($Opts{csv_sep});
        }
        if ($Opts{csv_quote}) {
            $csv->quote_char($Opts{csv_quote});
        }
        if ($Opts{csv_escape}) {
            $csv->escape_char($Opts{csv_escape});
        }
        if ($Opts{csv_loose}) {
            $csv->allow_loose_quotes(1);
            $csv->allow_loose_escapes(1);
        }
        $rows = [];
        while ( my $row = $csv->getline($fh) ) {
            push @$rows, $row;
        }
        $csv->eof or $csv->error_diag();
    } elsif ($ifmt eq 'tsv') {
        $rows = [];
        while (my $row = <$fh>) {
            chomp $row;
            push @$rows, [split /\t/, $row];
        }
    } elsif ($ifmt eq 'ini' || $ifmt eq 'iod') {
        my $reader;
        if ($ifmt eq 'ini') {
            require Config::IOD::INI::Reader;
            $reader = Config::IOD::INI::Reader->new;
        } else {
            require Config::IOD::Reader;
            $reader = Config::IOD::Reader->new;
        }
        my $content = do { local $/; scalar <$fh> };
        my $hoh = $reader->read_string($content);
        $rows = [];
        for my $section (sort keys %$hoh) {
            my $hash = $hoh->{$section};
            for my $key (sort keys %$hash) {
                push @$rows, [$key, $hash->{$key}];
            }
        }

    } elsif ($ifmt eq 'json') {
        require Data::Check::Structure;
        require JSON::MaybeXS;
        local $/;



( run in 0.738 second using v1.01-cache-2.11-cpan-39bf76dae61 )