gpt4 book ai didi

scope - 在子中通过名称获取符号的值

转载 作者:行者123 更新时间:2023-12-04 14:53:55 27 4
gpt4 key购买 nike

我正在制作一个包,我必须在子程序中通过其名称获取符号的值,而符号是在子程序之外定义的。

这是简化的代码,它按预期工作:

#! /usr/bin/env perl6 

sub dump_value($symbol) {
say ::("$symbol")
}

# usage:
my $x = 10;
dump_value('$x');

# expected output: 10
# actual output: 10

然后我将“dump_value”放在一个独立文件中,如下所示:
# somelib.pm6
unit module somelib;

sub dump_value($symbol) is export {
say ::("$symbol")
}
# client.pl6
#! /usr/bin/env perl6

use lib ".";
use somelib;

my $x = 10;

dump_value('$x');

编译器提示:
No such symbol '$x'
in sub dump_value at xxx/somelib.pm6 (somelib) line 3
in block <unit> at ./client.pl6 line 8

以下是一些实验。他们都没有成功。
say ::("MY::$symbol")

say ::("OUR::$symbol")

say ::("OUTER::$symbol")

say ::("CLIENT::$symbol")
...

那么如何修复代码呢?

更新:

谢谢! CALLERS::($symbol)解决了我原来的问题。但在更复杂的情况下,编译器再次提示:
# somelib.pm6
unit module somelib;

sub dump_value(@symbols) is export {
# output: 6
say CALLERS::('$x');

# error: No such symbol 'CALLERS::$x'
say @symbols.map({ CALLERS::($^id) } )
}

# client.pl6
#! /usr/bin/env perl6

use lib ".";
use somelib;

my $x = 6;
my $y = 8;

dump_value(<$x $y>);

再次更新:

使用 OUTER::CALLERS::($^id) .

一次又一次地更新:

在我将 'dump_value' 放入另一个 sub 后,它不再起作用了!
# somelib.pm6
unit module somelib;

sub dump_value(@symbols) is export {
say @symbols.map({ OUTER::CALLERS::($^id) } )
}

sub wrapped_dump_value(@symbols) is export {
dump_value(@symbols)
}
#! /usr/bin/env perl6

use lib ".";
use somelib;

my $x = 6;
my $y = 8;

# ouput: (6 8)
dump_value(<$x $y>);

# error: No such symbol 'OUTER::CALLERS::$x'
wrapped_dump_value(<$x $y>);

最佳答案

根据 the documentation :

An initial :: doesn't imply global. Here as part of the interpolation syntax it doesn't even imply package. After the interpolation of the ::() component, the indirect name is looked up exactly as if it had been there in the original source code, with priority given first to leading pseudo-package names, then to names in the lexical scope (searching scopes outwards, ending at CORE).



所以当你写 say ::("$symbol")dump_value()somelib包,它会先查找 $symbol在当前范围内,其值为 '$x'然后尝试查找 $x (也在当前范围内),但变量 $x定义在调用者的词法范围内,所以你得到 No such symbol '$x'错误。

您可以引用由 $symbol 的值给出的调用者的词法符号。使用:
CALLER::MY::($symbol);  # lexical symbols from the immediate caller's lexical scope

或者
 CALLERS::($symbol); # Dynamic symbols in any caller's lexical scope

the package documentation page .

关于scope - 在子中通过名称获取符号的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54520122/

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