Search code examples
perlhashdereference

How to dereference hash references


UPDATE: Everything I know about referencing/dereferencing came from here: http://www.thegeekstuff.com/2010/06/perl-array-reference-examples/

I'm working with a library that (from the library documentation):

Returns a reference to an array of hash references

This conceptually makes sense to me (i'm not new to programming) but doesn't make sense functionally (i'm, apparently, very new to perl).

Here's some code:

my $Obj  = QA::STK::ModuleImUsing->new(arguments, to, new);
$Obj->createClient();
$Obj->sync( ['/tmp/files/...']);
my $result = $Obj->method_in_question(['/tmp/files/ff-latest.xml']);

So far so good. $result now holds the reference to an array.

So when I do this:

print "Result: @{ $result} \n";

I get:

Result: HASH(0x20d95b0)

Lovely! But I still need to dereference the hash. However, here's where things get weird (or maybe they've already gotten weird?).

my $hash_ref = @{ $result};
print Dump($hash_ref));

I get this:

$VAR1 = 1;

Which...isn't what I was expecting at all.

Are my expectations wrong or am I dereferencing things in the wrong way?


Solution

  • If @$result is an array then your LHS must be a list. Otherwise $hashref will be assigned the array size.

    my ($hash_ref) = @{ $result};
    print Dump($hash_ref));