user2729360
user2729360

Reputation:

How to start hash of arrays and print out?

I want to start a hash of arrays and print out the values. I have tried this:

#!/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   

But i want:

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

Can anyone help me out?

Upvotes: 1

Views: 137

Answers (4)

fugu
fugu

Reputation: 6568

Try this:

#!/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
}

Output:

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

Upvotes: 1

shingo.nakanishi
shingo.nakanishi

Reputation: 2807

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";
}

Upvotes: 1

amon
amon

Reputation: 57600

Your problem is that you print a tab and a newline after each value here:

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

I guess you want to seperate the values by tabs, and want a newline at the end.

We can use the join function. It takes a separator and a list, then concatenates all items in the list with your separator in between:

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

So instead of that inner loop, you can write

print "Array: $number = ", join("\t", @{ $hash{$number} } ), "\n";

Upvotes: 1

wholerabbit
wholerabbit

Reputation: 11536

Here, $number is an element of keys %hash:

foreach my $number (keys %hash) {

And keys %hash is, sensibly enough, the keys of %hash: strings containing "one", "two", and "three". If you want to use numbers as keys instead, you can:

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

Which will correct part of your problem. The other part is where you insert the newline:

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

Instead:

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

Also notice I put the tab before the element.

Upvotes: 1

Related Questions