perl - printing hash variable values gives ARRAY(x

2019-08-29 13:04发布

问题:

This question already has an answer here:

  • What does it mean when you try to print an array or hash using Perl and you get, Array(0xd3888)? 3 answers

I have two arrays of the following form:

root rhino root root root root root root root root root root domainte root
stam rhino jam onetwo domante ftpsi jay testwp contra raul vnod foos raul bruce

Using help I got from SO, I have put both of them into a hash like so:

my %hash;
for my $idx (0 .. $#test2) {
push @{ $hash{ $test2[$idx] } }, $test3[$idx];}
print "<br /><br /><br /><br />";
print Dumper \%hash;

which gives the following output:

$VAR1 = { 'rhino' => [ 'rhino' ], 
          'domante' => [ 'raul' ],
          'root' => [ 'stam', 'jam', 'onetwo', 'domante', 'ftpsi', 
                      'jay', 'testwp', 'contra', 'raul', 'vnod', 
                      'foos', 'bruce' ] 
        };

Now push the key and values to 2 arrays like so:

my @q1 = keys %hash;
 my @q2 = values %hash;

 print "<br /><br /><br /><br />";
 print @q1;
 print "<br /><br /><br /><br />";
 print @q2;

While printing, I get the keys right, but the values print the following output:

ARRAY(0x9bf0b0)ARRAY(0x9bf1e8)ARRAY(0x9bf068)

How do I get all the values into arrays? What am I doing wrong?

Edit:

Here's what I tried:

foreach (@q1)
{       print @{$hash{$q1}};
        print "<br />";
}

but got no viable result.

回答1:

The values of your hash are all array references. You can tell from the Data::Dumper output because all the values are enclosed in [ ... ] brackets. To print out the array's contents, you'll need to dereference the array references.

There are a lot of ways to do that. Here's a concise way that you can modify for your needs:

print "@$_\n" for @q2;

$_ is an alias to an element of @q2, which you'll recall is an array reference. The expression @$_ dereferences the reference, returning the array. Putting @$_ in double quotes will print every element of the array with a space between the elements.



标签: arrays perl hash