Search code examples
perlhashdereference

How do I dereference a Perl hash reference that's been passed to a subroutine?


I'm still trying to sort out my hash dereferencing. My current problem is I am now passing a hashref to a sub, and I want to dereference it within that sub. But I'm not finding the correct method/syntax to do it. Within the sub, I want to iterate the hash keys, but the syntax for a hashref is not the same as a hash, which I know how to do.

So what I want is to do this:

sub foo {
    %parms = @_;
    foreach $keys (key %parms) { # do something };
}

but with a hashref being passed in instead of a hash.


Solution

  • I havn't actually tested the code at this time, but writing freehand you'll want to do something like this:

    sub foo {
        $parms = shift;
        foreach my $key (keys %$parms) { # do something };
    }