How do I dereference a Perl hash reference that's been passed to a subroutine?
13,830
Solution 1
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 };
}
Solution 2
Here is one way to dereference a hash ref passed to a 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 References quick reference and perlreftut
Solution 3
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 intro about references is here.
Solution 4
#!/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";
};
}
Author by
sgsax
Updated on July 02, 2022Comments
-
sgsax almost 2 years
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.