如何启动数组的哈希并打印出来?

时间:2013-08-30 09:07:45

标签: arrays perl hash

我想开始一个数组哈希并打印出值。我试过这个:

#!/usr/bin/perl
use strict;
use warnings;

my %hash = (
    one=> [ 'a', 'b', 'c', ],
    two => [ 'd', 'e', 'f', ],
    three => [ 'g', 'h', 'i', ],
);


foreach my $number (keys %hash) {
    print "Array: $number = ";
    foreach (@{$hash{$number}}) {
        print "$_\t\n";
    }
}

Array: three = g    
h   
i   
Array: one = a  
b   
c   
Array: two = d  
e   
f   

但我想:

Array1 a b c 
Array2 d e f
Array3 g h i

任何人都可以帮助我吗?

4 个答案:

答案 0 :(得分:1)

试试这个:

#!/usr/bin/perl -w
use strict;

my %hash = (
    array1 => [ 'a', 'b', 'c', ],
    array2 => [ 'd', 'e', 'f', ],
    array3 => [ 'g', 'h', 'i', ],
);

foreach my $key (sort keys %hash) { 
    print "Array: $key = ";
    foreach ( @ {$hash{$key} } ) {
        print "$_\t"; # Separate values by `tab`
    }
    print "\n"; # This newline was in the wrong loop in your code
}

输出:

Array: array1 = a   b   c   
Array: array2 = d   e   f   
Array: array3 = g   h   i

答案 1 :(得分:1)

此处,$numberkeys %hash

的元素
foreach my $number (keys %hash) {

keys %hash明显足够%hash:包含“one”,“two”和“three”的字符串。如果您想使用数字作为键,您可以:

my %hash = (
    1 => [ 'a', 'b', 'c', ],
    2 => [ 'd', 'e', 'f', ],
    3 => [ 'g', 'h', 'i', ],
);

这将纠正您的部分问题。另一部分是您插入换行符的位置:

foreach (@{$hash{$number}}) {
    print "$_\t\n";
}

相反:

foreach (@{$hash{$number}}) {
    print "\t$_";
}
print "\n";

另请注意,我将标签放在元素之前。

答案 2 :(得分:1)

您的问题是您在此处的每个值后打印标签和换行符:

foreach (@{$hash{$number}}) {
    print "$_\t\n";
}

我想您希望按选项卡分隔值,并希望结束的换行符。

我们可以使用join功能。它需要一个分隔符和一个列表,然后将列表中的所有项目与之间的分隔符连接起来:

 join "-", 1, 2, 3;  # "1-2-3"

因此,您可以编写

而不是内部循环
print "Array: $number = ", join("\t", @{ $hash{$number} } ), "\n";

答案 3 :(得分:1)

use strict;
my %hash = (
    Array1 => [ 'a', 'b', 'c', ],
    Array2 => [ 'd', 'e', 'f', ],
    Array3 => [ 'g', 'h', 'i', ],
);

for my $key (sort keys %hash) {
    my $text = join " ", @{$hash{$key}};
    print $key, " ",  $text, "\n";
}