John Levin
John Levin

Reputation: 41

Perl Hash Value

Im trying to print perl hash value but its printing the ARRAY().

foreach my $key (sort keys %myHash) {
    my $val = $myHash{$key};
    print "$key => $val\n";
}

The Output is printing like

172  ARRAY(0x1c42548)
199  ARRAY(0x1c42638)
209  ARRAY(0x1c63360)
299  ARRAY(0x1c63390)
325  ARRAY(0x1c634e0)

Upvotes: 3

Views: 175

Answers (1)

Greg Nisbet
Greg Nisbet

Reputation: 6994

Your values in your hash are themselves scalars pointing to arrays. Consider using Data::Dumper to print the value or if the elements of the arrays are scalars you can try something like the following.

The two builtin Perl collections, hashes and arrays, do not nest directly. They contain scalars which may be strings/numbers or references to hashes or arrays. There can also be references to functions and other more exotic things.

# Extract the array as an array and interpolate.

foreach my $key (sort keys %myHash) {
    my @val = @{ $myHash{$key} };
    print "$key => @val\n";
}

Data::Dumper exposes an option to sort keys.

# sample program using Data::Dumper

use strict;
use warnings;
use Data::Dumper;

local $Data::Dumper::Sortkeys = 1;

# obj is a reference to a hash.
my $obj = { 1 => 2, 3 => 4};

print Dumper($obj);

which prints

$VAR1 = {
          '1' => 2,
          '3' => 4
        };

Upvotes: 5

Related Questions