1

我有一个带有特定数据集的哈希。我需要操纵哈希值,以便获得如下结果:

预期输出:

key_1=Cell1
Val_1=C3#C4#C1#C2

脚本:

#!/usr/bin/perl

use strict; use warnings;

use Data::Dumper;
use List::Util qw /uniq/;

my %hash = (
        'Cell1' => {
                    'A' => [ 'C1','C2','C1','C2' ],
                    'B' => [ 'C3','C3','C4','C4' ]
        }
);

print Dumper(\%hash);

my $i = 0;

foreach my $key (keys %hash) {
    ++$i;
    print "key_$i=$key\n";
    foreach my $refs (keys %{ $hash{$key} }) {
        print "Val_$i=", join('#', uniq @{$hash{$key}{$refs}})."\n";    
    }
}

电流输出:

key_1=Cell1
Val_1=C3#C4
Val_1=C1#C2

我怎样才能在这里得到预期的输出?

4

2 回答 2

2

@cells您可以在打印之前使用附加数组 ( ) 来存储值:

foreach my $key (keys %hash) {
    ++$i;
    print "key_$i=$key\n";
    my @cells;
    foreach my $refs (keys %{ $hash{$key} }) {
        push @cells, @{$hash{$key}{$refs}};
    }
    print "Val_$i=", join('#', uniq @cells)."\n";    
}

印刷:

key_1=Cell1
Val_1=C3#C4#C1#C2

由于您从哈希中检索密钥,因此无法保证顺序。您可以使用sort使订单可预测。

于 2021-03-09T18:39:50.040 回答
2

显示的代码一次使用每个键的值(for A,然后 for B...)。相反,使用map所有键的列表组装所有值

my $i = 0;
for my $key (keys %hash) { 
    ++$i;
    say "key_$i=$key";
    say "Val_$i=", 
        join "#", uniq map { @{ $hash{$key}->{$_} } } keys %{$hash{$key}};
}
于 2021-03-09T18:40:02.723 回答