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

守給你的承諾、 提交于 2019-12-05 07:26:14
cyberconte

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 };
}

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


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.

#!/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";
    };
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!