gpt4 book ai didi

perl - 在不创建本地副本的情况下取消引用哈希

转载 作者:行者123 更新时间:2023-12-05 01:03:42 25 4
gpt4 key购买 nike

我下面第 9 行的代码创建了哈希的本地副本。对 %d 的任何更改都不会提供对全局 %h 变量的更改(第 5 行)。我必须使用引用(第 8 行)来提供对 %h 的更改。

有没有办法在不创建本地副本的情况下取消引用子中的哈希?
我在问,因为我有许多引用的复杂记录,并且通过取消引用在它周围导航会容易得多。

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

----------------

感谢您的回复。

问题是我可以在 sub 中对 %h 进行某种“别名/绑定(bind)”吗?
我想用 %d 更改子中 %h 的上下文。
每当我创建 %d 时,他都会制作 %h 的本地副本 - 有什么办法可以避免这种情况,还是我必须一直使用引用?

----------------

再来一次 :) 我知道 $href 的工作原理。我阅读教程/手册/文档等。
我没有在那里找到答案 - 我认为这是不可能的,因为它没有写在那里,但谁知道。

我想完成这样的行为:
  6 sub a {
7 $h{"1"}=2;
8 }

这相当于:
  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

现在如何在 %d 的帮助下做到这一点 - 这真的可能吗?
6 sub a {
7 my %d = XXXXXXXXX
.. }

我应该在 XXXXXXXXX 下放置什么来指向 %h 而不创建本地副本?

最佳答案

要创建该值的本地别名,您需要使用 Perl 的包变量,可以使用 typeglob 语法(和 local 来确定别名的范围)对其进行别名:

#!/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

这是一种相当先进的技术,因此请务必阅读 local 上的 Perl 文档。和 typeglobs这样您就可以准确了解发生了什么(特别是,在 a 之后从 local 子例程中调用的任何子程序也将在范围内具有 %alias,因为 local 表示动态范围。本地化将在 a 返回。)

如果可以安装 Data::Alias或来自 CPAN 的其他别名模块之一您可以避免包变量并创建一个词法别名。上面的方法是在没有额外模块的情况下完成它的唯一方法。

关于perl - 在不创建本地副本的情况下取消引用哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2972521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com