开发者

When accessing modules

开发者 https://www.devze.com 2023-03-08 06:12 出处:网络
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....

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.


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 of main, i.e. it is short for $main::var_name. In the case of your example, where you have package main; first, you need to stipulate that the namespace is test, rather than main, 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 of main::sub_name()... in the same way, no sigil is needed to call package::sub().

*References as to the use of &:

  • Perl Monks discussion
  • Perl::Critic dislikes it, following on from Perl Best Practices
  • Per perldoc, using & with a function name allows you to deviate from the usual behaviour. This can result in subtle bugs.
0

精彩评论

暂无评论...
验证码 换一张
取 消