Below is a code that dumps an SQL query to an aligned text table format.
sub sql_command {
my ($self,$str) = @_;
my $s = $self->{_db}->prepare($str) or die $!;
$s->execute() or die $!;
my $table;
push @$table, [ map { defined $_ ? $_ : "undef" } @{$s->{'NAME'}}];
while(my $row = $s->fetch) {
push @$table, [ map{ defined $_ ? $_ : "undef" }@$row ];
}
return box_format($table);;
}
sub box_format {
my $table = shift;
my $n_cols = scalar @{$table->[0]};
my $tb = Text::Table->new(\'| ', '', (\' | ','')x($n_cols-1), \' |+');
$tb->load(@$table);
my $rule = $tb->rule(qw/- +/);
my @rows = $tb->body();
return $rule, shift @rows, $rule, @rows, $rule
if @rows;
}
The output is as expected. But performance-wise, it takes about ~30sec to process on about an output file of size ~5MB.
Is there a better way to achieve that in terms of performance?
Thanks!