views:

484

answers:

4

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.

Any pointers (pun not intended) are welcome.

Thanks.

+3  A: 

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 };
}
cyberconte
Using shift instead of @_ did the trick, and of course, using a scalar instead of a hash for the variable. Working code:sub foo { $parms = shift; foreach $key (keys %$parms) { print "$key : $$parms{$key}\n"; }}Thanks!
sgsax
`$parms->{$key}` is probably slightly preferred to `$$parms{$key}`
toolic
`shift` vs. `@_` is not relevant. `my ($hashref) = @_;` will work just as well.
Andrew Medico
+1  A: 

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

toolic
Thanks for the links. I've been looking at the perlreftut page, amongst others, but am still trying to figure it all out.
sgsax
+1  A: 

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.

Neeraj
Thanks for the link. I've been using that one as a reference, but I still don't quite have a full grasp of it yet.
sgsax
A: 
#!/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";
    };
}
chris d
Eep, didn't see toolics reply until just now. ;x
chris d
I'd say his naming is better (naming the hashref as href).
chris d