I the code bellow line 9 creates a local copy of a hash. Any changes to the %d will not provide changes to global %h variable (line: 5). I have to use reference (line: 8) to provide changes to %h.
Is there any way to dereference hash in a sub without creating a local copy?
I am asking since I have complicated record with many references and navigating around it with dereferences would be much easier.
1 #!/usr/bin/perl -w
2 use strict;
3 use warnings;
4
5 my %h;
6 sub a {
7
8 my $href = shift;
9 my(%d) = %{$href}; # this will make a copy of global %h
10
11 $$href{1}=2; # this will make a change in global %h
12 $d{2}=2; # this will not a change in global %h
13 }
14 a(\%h);
15 print scalar (keys %h) . "\n";
—————-
Thanks for the replies.
The question is can I make some kind of “alias/bind” to %h in a sub.
I would like to change the context of %h in a sub with %d.
Whenever I create %d he makes local copy of %h – is there any way to avoid that or do I have to use references all the time?
—————-
One more time 🙂 I know how $href’s work. I read tutorial / manuals / docs etc.
I didn’t find the answer there – I assume that this is not possible since it wasn’t written there, but who knows.
I want to accomplish such behavior:
6 sub a {
7 $h{"1"}=2;
8 }
Which is equivalent to that:
6 sub a {
8 my $href = shift;
11 $$href{1}=2; # this will make a change in global %h
11 $href->{1}=2; # this will make a change in global %h
Now how to do that with the help of %d – is it actually possible?
6 sub a {
7 my %d = XXXXXXXXX
.. }
What should I put under XXXXXXXXX to point to %h without creating a local copy?
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
localto scope the alias):This is a fairly advanced technique, so be sure to read the Perl docs on
localandtypeglobsso you understand exactly what is going on (in particular, any subs called from within theasubroutine after thelocalwill also have%aliasin scope, sincelocaldenotes a dynamic scope. The localization will end whenareturns.)If you can install
Data::Aliasor one of the other aliasing modules fromCPANyou can avoid the package variable and create a lexical alias. The above method is the only way to do it without additional modules.