如何使用Perl6 :: Form的引用?

时间:2017-03-15 20:12:38

标签: perl reference

我正在尝试使用Perl6::Form打印表格数据,但我不确定如何从散列引用输出数据。这是我到目前为止所尝试的:

#!/usr/bin/perl
use Perl6::Form;

my @alerts; 

push @alerts, { site => "192.168.0.1", status => "200", id => "QWE" };
push @alerts, { site => "192.168.0.2", status => "500", id => "QER" };

print form
        ' ====================================== ',
        '| ID          |    SITE    | STATUS    |',
        '|-------------+------------+-----------|',
        '| {[[[[[[[[[} |{[[[[[[[[[} | {>>>>>>>} |',
           \@alerts{id}, \@alerts{site},\@alerts{status},
        ' ====================================== ';

1 个答案:

答案 0 :(得分:7)

您需要并行数组。

my @ids      = map { $_->{id}     } @alerts;
my @sites    = map { $_->{site}   } @alerts;
my @statuses = map { $_->{status} } @alerts;

print
   form
      '+=======================================+',
      '| ID          | SITE        | STATUS    |',
      '|-------------+-------------+-----------|',
      '| {[[[[[[[[[} | {[[[[[[[[[} | {>>>>>>>} |',
         \@ids,        \@sites,      \@statuses,
      '+=======================================+';

我们可以消除代码重复。

my %dbf;   # Data by field
for my $field (qw( id site status )) {
   $dbf{$field} = [ map { $_->{$field} } @alerts ];
}

print
   form
      '+=======================================+',
      '| ID          | SITE        | STATUS    |',
      '|-------------+-------------+-----------|',
      '| {[[[[[[[[[} | {[[[[[[[[[} | {>>>>>>>} |',
         $dbf{id},     $dbf{site},   $dbf{status},
      '+=======================================+';