perl – 如何打印DBIx :: Class结果?

前端之家收集整理的这篇文章主要介绍了perl – 如何打印DBIx :: Class结果?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想像这样漂亮地打印DBIx :: Class :: ResultSet结果:

my $schema = MyDatabase::Main->connect('dbi:sqlite:db/example.db');
my $rs = $schema->resultset('Track')->all()
# then print $rs with all of those feilds

我找到了DBIx :: sqlCrosstab :: Format类,但它似乎只适用于自己的查询.

解决方法

我不知道任何DBIC漂亮的打印模块,但它很容易从CPAN上的任何文本,html或其他类型的表格输出模块实现.

下面是我使用Text::Table快速工作示例

use 5.012;
use warnings;
use List::MoreUtils 'zip';
use Text::Table;

# my database with Album schema from DBIx::Class::Manual::Intro
use MySchema;
my $db     = MySchema->connect( "DBI:sqlite:myschema_db" );
my $album  = $db->resultset( 'Album' );

# get column names for the Album table
my @cols   = $album->result_source->columns;

# create header with these column names
my $table  = Text::Table->new( header( @cols ) );

# add each Album row to table output
while (my $cd = $album->next) {
    $table->add( map { $cd->get_column( $_ ) } @cols );
}

print $table;    # => tabular text output

# adds | separator between header labels
sub header {
    my @sep = (\' | ') x @_;
    zip @_,@sep;
}

这将输出以下测试数据:

albumid | artist      | title          | rank | 
1       | Lou Reed    | Transformer    |      | 
2       | Lou Reed    | Berlin         |      | 
3       | David Bowie | Ziggy Stardust |      | 
4       | Japan       | Tin Drum       |      |

/ I3az /

猜你在找的Perl相关文章