开发者

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

开发者 https://www.devze.com 2022-12-20 06:14 出处:网络
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/synt

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 {
    %pa开发者_运维百科rms = @_;
    foreach $keys (key %parms) { # do something };
}

but with a hashref being passed in instead of a hash.


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


Dereference the original reference, but use it as another one / its copy, what is also very common or more common.

sub foo {
    my ($parmsHashRef , $parmsArrRef) = @_;

    # for hashes,   \%$parmsHashRef - would not work (seems would be a "reference" on another reference already)
    my $newDetachedHashRef = {%$parmsHashRef} # or just = {$parmsHashRef}
    # for arrays ,  \@$parmsArrRef - would not work
    my $newDetachedArrRef = [@$parmsArrRef] # or just = [$parmsArrRef]
}
0

精彩评论

暂无评论...
验证码 换一张
取 消