Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 945
sgsax Avatar asked Feb 17 '10 17:02

sgsax


People also ask

How do I dereference a hash reference in Perl?

Dereference a HASH First we print it out directly so you can see it is really a reference to a HASH. Then we print out the content using the standard Data::Dumper module. Then we de-reference it by putting a % sign in-front of it %$hr and copy the content to another variable called %h.

How do I dereference an array reference in Perl?

Dereferencing an array If you have a reference to an array and if you would like to access the content of the array you need to dereference the array reference. It is done by placing the @ symbol (the sigil representing arrays) in-front of the reference.

How do I print a hash reference value in Perl?

Write the hash syntax as you would have without references, and then replace the name of the hash with a pair of curly braces surrounding the thing holding the reference. For example, to pick a particular value for a given key, use: my $name = $ gilligan_info { 'name' }; my $name = $ { $hash_ref } { 'name' };


1 Answers

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 };
}
like image 148
cyberconte Avatar answered Oct 11 '22 12:10

cyberconte