dereferencing hash without creating a local copy

心已入冬 提交于 2019-12-05 20:36:27

To create a local alias of the value, you need to use Perl's package variables, which can be aliased using the typeglob syntax (and local to scope the alias):

#!/usr/bin/perl -w
use strict;
use warnings;

my %h;

sub a {
    my $href = shift;

    our %alias; # create the package variable (for strict)

    local *alias = $href;
        # here we tell perl to install the hashref into the typeglob 'alias'
        # perl will automatically put the hashref into the HASH slot of
        # the glob which makes %alias refer to the passed in hash.
        # local is used to limit the change to the current dynamic scope.
        # effectively it is doing:  *{alias}{HASH} = $href

    $$href{1}=2;     # this will make a change in global %h
    $alias{2}=2;     # this will also make a change in global %h
}
a(\%h);
print scalar (keys %h) . "\n";  # prints 2

This is a fairly advanced technique, so be sure to read the Perl docs on local and typeglobs so you understand exactly what is going on (in particular, any subs called from within the a subroutine after the local will also have %alias in scope, since local denotes a dynamic scope. The localization will end when a returns.)

If you can install Data::Alias or one of the other aliasing modules from CPAN you can avoid the package variable and create a lexical alias. The above method is the only way to do it without additional modules.

sud03r

Two ways of using a hash reference:

  1. One you yourself were using

    $$href{'key2'} = "key2";
    
  2. Pointed out above:

    $href->{'key1'} = "key1";
    

http://perldoc.perl.org/perlreftut.html

Does this help you

$href->{1} = 2;
print scalars (keys %{$href});

?

Following code shows how to dereference using the arrow operator (and yes, without creating a local variable)

Read this for a tutorial on dereferencing and the different types of dereferencing possible.

use warnings;
use Data::Dumper::Simple;

my %h;
sub a {
    my $href = shift;

    #dereference using the arrow operator - *preferred*
    $href->{name} = "John"; 

}

a(\%h); #Passing the reference of the hash
print Dumper(%h);

Why do you need to pass the hash which is a global, as an argument to the sub-routine in the first place?

  1. Avoid using global variables.
  2. Preferably, don't change the state of any variables after they have been assigned.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!