How to dereference a Perl hash link that has been passed to a routine?

I'm still trying to deal with hash dereferencing. My current problem is that I pass hashref to sub, and I want to dereference it in that sub. But I do not find the correct method / syntax for this. Inside the sub, I want to iterate the hash keys, but the syntax for hashref is not the same as the hash that I know how to do.

So what I want to do is:

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

but with a hashref instead of a hash.

Any pointers (no pun intended) are welcome.

Thanks.

+6
perl dereference hash
source share
4 answers

At the moment, I really have not tested the code, but by hand writing you want to do something like this:

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

Here is one way to dereference the hash link passed to sub:

 use warnings; use strict; my %pars = (a=>1, b=>2); foo(\%pars); sub foo { my ($href) = @_; foreach my $keys (keys %{$href}) { print "$keys\n" } } __END__ a b 

See also Quick Access Links and perlreftut

+2
source share
 sub foo { my $params = $_[0]; my %hash = %$params; foreach $keys (keys %hash) { print $keys; } } my $hash_ref = {name => 'Becky', age => 23}; foo($hash_ref); 

Also a good introduction regarding links here .

+2
source share
 #!/usr/bin/perl use strict; my %params = ( date => '2010-02-17', time => '1610', ); foo(\%params); sub foo { my ($params) = @_; foreach my $key (keys %$params) { # Do something print "KEY: $key VALUE: $params{$key}\n"; }; } 
+1
source share

All Articles