彼此相邻地打印键和哈希值

时间:2018-07-24 13:10:06

标签: perl hash

我有一个像这样的哈希

my %results = (
    'Ende Deaktiviere PKonten' => [
                                      '31.05.2018 03:28:33',
                                      '01.06.2018 03:54:18',
    ],
    'Ende Monatswechsel P-Konten' => [
                                         '31.05.2018 03:34:24',
                                         '01.06.2018 04:29:05',
    ]
);

我想以这种格式打印它:

'Ende Deaktiviere PKonten' 'Ende Monatswechsel P-Konten' 
'31.05.2018 03:28:33'       '31.05.2018 03:34:24'
'01.06.2018 03:54:18'       '01.06.2018 04:29:05'

有人可以帮我吗?

我尝试过:

foreach my $key (keys %results) {
            $N = scalar @{ $results{$key} };

            for my $i (0..($N-1)) {
                    print "i= $i , @{ $results{$key} }[$i]" ;
                    print "\n";
            }
print "\t";
}

输出

31.05.2018 03:37:47 01.06.2018 04:53:44 02.06.2018 03:37:14 07.06.2018 03:21:04 08.06.2018 03:40:04 31.05.2018 03:37:30 01.06.2018 04:53:23 02.06.2018 03:36:58 07.06.2018 03:20:51 08.06.2018 03:39:51

3 个答案:

答案 0 :(得分:0)

这应该做您想要的。首先打印键,然后从每个数组一次打印一个值:

use strict;
use warnings;

my $hash = {
    'Ende Deaktiviere PKonten' => [
        '31.05.2018 03:28:33',
        '01.06.2018 03:54:18',
    ],
    'Ende Monatswechsel P-Konten' => [
        '31.05.2018 03:34:24',
        '01.06.2018 04:29:05',
    ]
};
my $arrLingth = @{$hash->{(keys %$hash)[0]}};
foreach my $key(keys %$hash) {
    printf "%25s", $key . "\t";
}
print "\n";
for(my $i=0; $i<$arrLingth; $i++) {
    foreach my $key(keys %$hash) {
        printf "%25s", $hash->{$key}->[$i] . "\t";
    }
    print "\n";
}

答案 1 :(得分:0)

尽管我可能会回答一个糟糕的问题而感到不满意,但这是我的解决方法

如我的“提示”中所述,这将构建一个列信息数组并在打印时对其进行转置。许多代码都涉及到printf格式的推广,而且可能会更短

请注意,这些列将没有特定的顺序,因为哈希在设计上固有地无序

use strict;
use warnings 'all';

use List::Util 'max';

my %results = (
    'Ende Deaktiviere PKonten'    => [ '31.05.2018 03:28:33', '01.06.2018 03:54:18' ],
    'Ende Monatswechsel P-Konten' => [ '31.05.2018 03:34:24', '01.06.2018 04:29:05' ],
);

{
    my @columns = map [ $_, @{ $results{$_} } ], keys %results;

    my $w    = max map length, map @$_, @columns;
    my $imax = max map $#$_, @columns;
    my $fmt  = join(' ', ("%-${w}s") x @columns) . "\n";

    for my $i ( 0 .. $imax ) {
        printf $fmt, map $_->[$i] // '', @columns;
    }
}

输出

Ende Monatswechsel P-Konten Ende Deaktiviere PKonten   
31.05.2018 03:34:24         31.05.2018 03:28:33        
01.06.2018 04:29:05         01.06.2018 03:54:18        

答案 2 :(得分:-1)

您可以尝试:

say join "\t", map {"'$_'"} keys %results;

my $N = scalar @{ $results{ (keys %results)[0] } };
for my $i (0..($N - 1)) {
    my @row;
    for ( keys %results ) {
        push @row, $results{$_}[$i];
    }
    say join "\t", map {"'$_'"} @row;
}