访问模块时
我有一个关于包、模块和语法的问题。当您访问同一文件中的包时,我注意到您会使用类似...
package test;
$testVar="This is a test";
#and to access it using..
package main;
print($test::testVar);
或简单的...
package test;
print($testVar);
但是,当我使用此语法与模块一起使用时,发送参数,我应该省略 $ from打印功能的开始,但上面我没有。我注意到它不起作用,否则我不知道为什么。我的材料没有澄清。
require module;
print(package::sub("argument"));
这是为什么?。我很困惑。
I have a question about packages, modules and syntax. When you access a package in the same file I notice you'd use something like....
package test;
$testVar="This is a test";
#and to access it using..
package main;
print($test::testVar);
or simply...
package test;
print($testVar);
Yet when I use this syntax for use with a module, sending an argument, I am supposed to ommit the $ from the start of the print function, yet above I don't. I noticed it didn't work otherwise and I don't know why. My materials don't clarify.
require module;
print(package::sub("argument"));
Why is that?. I'm confused.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的美元符号是一个印记,表明命名变量是一个标量。
如果前面没有
package
声明,则使用$var_name
包含main
的隐含命名空间,即它是$ 的缩写main::var_name
。在您的示例中,您首先有package main;
,您需要规定命名空间是test
,而不是main
,所以$test::testVar
是必需的。对于函数调用,您不需要使用印记。如果这样做,您将使用与号 (
&
),但在调用函数时使用与号已不再受到许多程序员的青睐。*与以前一样,
sub_name()
是main::sub_name()
的缩短版本...同样,调用package::sub()
不需要任何印记。*关于
&
使用的参考:&
带有函数名称可以让您偏离通常行为。这可能会导致微妙的错误。The dollar sign here is a sigil that indicates that the named variable is a scalar.
If there is no preceding
package
declaration, the use of$var_name
contains an implied namespace ofmain
, i.e. it is short for$main::var_name
. In the case of your example, where you havepackage main;
first, you need to stipulate that the namespace istest
, rather thanmain
, so$test::testVar
is required.For a function call, you do not need to use a sigil. If you did, you would use the ampersand (
&
), but using ampersands when calling functions has fallen out of favour with many programmers.*As before,
sub_name()
is a shortened version ofmain::sub_name()
... in the same way, no sigil is needed to callpackage::sub()
.*References as to the use of
&
:&
with a function name allows you to deviate from the usual behaviour. This can result in subtle bugs.